Phase 0: Fundament für Inhaus
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m14s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 1m12s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 1m7s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 1m19s
CI / PHP 8.3 / mysql:8.0 (pull_request) Successful in 1m32s
CI / PHP 8.4 / mysql:8.0 (pull_request) Successful in 1m22s
CI / PHP 8.4 / mysql:8.4 (pull_request) Successful in 1m32s
CI / PHP 8.3 / mysql:8.4 (pull_request) Successful in 1m35s
CI / Build-Artefakte aktuell (pull_request) Failing after 1m7s

- Laravel 13 mit Filament 5 (Admin), Inertia 3 + Vue 3 + Vuetify 4 (Material 3)
- Anmeldung über Fortify (Login, Passwort vergessen/ändern), keine Selbstregistrierung
- Profil mit Profilbild (WebP in festen Größen), Personenseiten, Header mit Avatar-Menü
- Material-3-Farbschema aus der Primärfarbe, hell/dunkel/System pro Person
- Basis-Branding (Portalname, Logo, Primärfarbe) im Admin unter „Erscheinungsbild“
- Benutzerverwaltung im Admin, Zugang vorläufig über is_admin
- vendor/ (ohne Dev-Pakete) und Frontend-Build mitversioniert, Dev-Pakete in vendor-dev/
- PHPUnit-Tests gegen MySQL/MariaDB, Forgejo-CI-Matrix, Docker-Entwicklungsumgebung
- VERSION, CHANGELOG.md und CONTRIBUTING.md mit Release-Ablauf

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-25 20:35:30 +00:00
parent 7197eaebf2
commit 9c0f8de791
15771 changed files with 1564103 additions and 5 deletions

75
vendor/livewire/livewire/CLAUDE.md vendored Normal file
View file

@ -0,0 +1,75 @@
# Project Overview
Livewire is a full-stack framework for Laravel. It allows you to build dynamic front-end applications without leaving the comfort of PHP/Laravel/Blade.
It is similar to projects like Phoenix Liveview however it isn't "live" in that it doesn't use real-time connections like websockets. Just simple http requests.
It renders on the server and uses morphing algorithm to path the DOM with updates from the server.
It "dehydrates" the state of a component into a JS-consumable object that is passed back to the server to be "hydrated" during the next request.
# Tech Stack
- Laravel + PHP + Vanilla JS
- JS Bundling: esbuild
# Project Structure
```
src/ → The PHP source files
- Features/ → Individual ~modules to isolate features
js/ → The JavaScript source files
tests/ → A smattering of PHP tests however, most tests are inside their src/Feature directories
```
# Development Workflow
## Setup
Run `composer setup` to install all dependencies (PHP, JS, ChromeDriver).
## Build JS assets
Run `npm run build` to bundle the JS
**IMPORTANT:** Do not commit `dist/` files. They are built in CI.
# Code Patterns
- Write JavaScript without semicolons
- Always use `let` (no `const`)
- Strive for single-word features and affordances (ex. `wire:click.stop` instead of `wire:click.stop-propagation`)
# Testing
Most browser and unit tests live inside of feature directories for example:
src/Features/SupportSlots/[UnitTest.php|BrowserTest.php]
```bash
composer test # all tests
composer test:unit # unit tests only
composer test:browser # browser tests (headless)
composer test:browser:headed # browser tests (opens Chrome)
composer test:browser -- --filter="SupportCSP" # specific browser tests
```
**IMPORTANT:** Never run the full Livewire browser test suite — it takes too long. Always use `--filter` to run only the specific tests relevant to your changes. The full suite runs in CI.
# Releasing
## Bumping Alpine (optional)
If you need to update the Alpine.js dependency before a release:
```bash
npm run bump-alpine
```
Then commit the updated `package.json` and `package-lock.json`.
## Creating a release
1. Go to **Actions → "Release" → "Run workflow"**
2. Enter the version number (e.g. `4.3.0` — the `v` prefix is added automatically)
3. The workflow installs deps, builds assets, runs JS tests, creates a tag with the built `dist/` files, and creates a GitHub Release with auto-generated notes

9
vendor/livewire/livewire/LICENSE.md vendored Normal file
View file

@ -0,0 +1,9 @@
## MIT License
Copyright © Caleb Porzio
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View file

@ -0,0 +1,230 @@
# wire:model Modifier Layering PRD
## Problem
`wire:model` modifiers (`.blur`, `.change`, `.debounce`) only control network request timing. Ephemeral (client-side) state ALWAYS syncs immediately as user types. Users can't delay ephemeral sync until blur/enter/change.
## Feature
Split modifiers into two layers: modifiers BEFORE `.live` control ephemeral sync timing (forwarded to x-model), modifiers AFTER `.live` control network timing. Breaking change for v4.
## Before
```blade
wire:model {{-- ephemeral immediate, no network --}}
wire:model.blur {{-- ephemeral immediate, network on blur --}}
wire:model.live {{-- ephemeral immediate, network debounced --}}
wire:model.live.debounce.500ms {{-- ephemeral immediate, network debounced 500ms --}}
```
- All modifiers only affect network layer
- No way to control ephemeral sync timing
- `.blur`/`.change` don't affect when x-model syncs
## After
```blade
wire:model {{-- ephemeral immediate, no network --}}
wire:model.blur {{-- ephemeral on blur, no network --}}
wire:model.change {{-- ephemeral on change, no network --}}
wire:model.enter {{-- ephemeral on enter, no network --}}
wire:model.blur.enter {{-- ephemeral on blur OR enter, no network --}}
wire:model.live {{-- ephemeral immediate, network debounced --}}
wire:model.live.blur {{-- ephemeral immediate, network on blur (OLD .blur behavior) --}}
wire:model.blur.live {{-- ephemeral on blur, network on blur --}}
wire:model.blur.live.debounce.500ms {{-- ephemeral on blur, network debounced 500ms after --}}
```
- Modifiers before `.live` → forwarded to x-model (controls ephemeral sync)
- Modifiers after `.live` → handled by Livewire (controls network)
- Everything chains sequentially: ephemeral syncs first, then network fires
## Relevant Files
- `js/directives/wire-model.js` — main implementation (lines 1-186)
- `node_modules/alpinejs/src/directives/x-model.js` — reference for how Alpine handles `.blur`/`.change`/`.enter` (lines 58-98)
- `src/Features/SupportDataBinding/BrowserTest.php` — existing browser tests
## Current Logic (wire-model.js:34-82)
```js
let isLive = modifiers.includes('live')
let isLazy = modifiers.includes('lazy') || modifiers.includes('change')
let onBlur = modifiers.includes('blur')
// ... these only control WHEN update() is called for network
// x-model always gets modifiers minus 'lazy','defer','debounce','throttle'
// meaning .blur/.change still get forwarded but DON'T affect ephemeral sync
// because wire:model uses get/set object pattern, not event listeners
```
Problem: `getModifierTail()` forwards `.blur` to x-model, but wire:model uses getter/setter pattern (`x-model.blur() { get(), set() }`), not Alpine's event-listener approach. So Alpine's `.blur` modifier has no effect.
## Changes Needed
1. **Parse modifiers into two groups** — split at `.live` boundary
- `ephemeralModifiers` = everything before `.live`
- `networkModifiers` = everything after `.live`
2. **Create extraction function** with clean interface:
```js
let {
ephemeralModifiers, // forwarded to x-model tail
onEphemeralSync, // callback when ephemeral state changes
shouldSendNetwork, // fn to check if network should fire
} = parseWireModelModifiers(modifiers)
```
3. **Forward ephemeral modifiers to x-model** — these get added to `x-model.blur.change.enter` etc.
4. **Add event listeners for network triggers** — if network modifiers include `.blur`, add `@blur` handler. Same for `.change`, `.enter`.
5. **Handle debounce/throttle at network layer** — wrap network callbacks in debounce/throttle based on network modifiers.
6. **x-model set() callback triggers network** — when x-model syncs (based on its modifiers), check if `.live` is present and call network update.
### Implementation Sketch
```js
directive('model', ({ el, directive, component, cleanup }) => {
let { expression, modifiers } = directive
// Split modifiers at .live boundary
let liveIndex = modifiers.indexOf('live')
let ephemeralModifiers = liveIndex === -1 ? modifiers : modifiers.slice(0, liveIndex)
let networkModifiers = liveIndex === -1 ? [] : modifiers.slice(liveIndex + 1)
let isLive = liveIndex !== -1
// Build x-model modifier tail from ephemeral modifiers
let xModelTail = buildModifierTail(ephemeralModifiers)
// Build network update function with debounce/throttle
let networkUpdate = buildNetworkUpdate(networkModifiers, component, expression, el, directive)
// Determine network trigger events
let networkTriggers = extractNetworkTriggers(networkModifiers)
Alpine.bind(el, {
['@blur']() {
if (networkTriggers.blur) networkUpdate()
},
['@change']() {
if (networkTriggers.change) networkUpdate()
},
['@keydown.enter']() {
if (networkTriggers.enter) networkUpdate()
},
['x-model' + xModelTail]() {
return {
get() {
return dataGet(component.$wire, expression)
},
set(value) {
dataSet(component.$wire, expression, value)
// If live with no specific triggers, fire on every sync
if (isLive && networkTriggers.immediate) {
networkUpdate()
}
},
}
}
})
})
```
## Decisions
- **Breaking change in v4** — acceptable since v4 is ~2 weeks old
- **`.live` is the delimiter** — everything before controls ephemeral, after controls network
- **Modifiers compound** — `.blur.enter` means blur OR enter (both trigger sync)
- **Network inherits ephemeral timing by default** — if no network modifiers, network fires when ephemeral syncs
- **`.live` alone = debounced immediate** — current behavior, ephemeral immediate + network debounced
- **`.live.blur` = ephemeral immediate, network on blur** — preserves old `.blur` behavior for migration
- **Empty network modifiers with `.live`** — means "fire network when ephemeral syncs" (for `.blur.live`)
## Test File
`src/Features/SupportDataBinding/BrowserTest.php` (add to existing file)
### New Test Cases
Single consolidated test with multiple scenarios:
1. `wire:model` — ephemeral syncs on input, no network
2. `wire:model.blur` — ephemeral syncs on blur only, no network
3. `wire:model.change` — ephemeral syncs on change only, no network
4. `wire:model.enter` — ephemeral syncs on enter only, no network
5. `wire:model.blur.enter` — ephemeral syncs on blur OR enter, no network
6. `wire:model.live` — ephemeral immediate, network debounced
7. `wire:model.live.blur` — ephemeral immediate, network on blur (old behavior)
8. `wire:model.blur.live` — ephemeral on blur, network on blur
9. `wire:model.blur.live.debounce.500ms` — ephemeral on blur, network debounced
9. `wire:model.blur.live.throttle.500ms` — ephemeral on blur, network throttled
Each scenario: type into input, verify ephemeral state via `x-text="$wire.prop"`, verify server state via `{{ $prop }}`, trigger blur/enter/change, verify both states.
## Manual Testing
1. **Test ephemeral-only blur**
- Create input with `wire:model.blur="title"`
- Type "hello" — ephemeral should NOT update
- Click away — ephemeral updates to "hello"
- Server still shows old value
2. **Test network on blur (old behavior)**
- Create input with `wire:model.live.blur="title"`
- Type "hello" — ephemeral updates immediately
- Click away — network request fires, server updates
3. **Test full blur.live**
- Create input with `wire:model.blur.live="title"`
- Type "hello" — ephemeral stays unchanged
- Click away — ephemeral updates, network fires, server updates
## Documentation
**File:** `docs/wire-model.md`
**Section to modify:** "Customizing update timing" (line ~51) and "Reference" table (line ~291)
**Add:**
- Explain modifier layering concept
- Update examples to show new syntax
- Add migration note about breaking change
- Update modifier reference table
## Git
**Commit message:**
```
feat(wire:model): control ephemeral sync timing with modifiers
BREAKING: Modifiers before .live now control ephemeral (x-model) sync
timing, not just network timing. Previous .blur behavior is now .live.blur.
- wire:model.blur syncs ephemeral on blur (no network)
- wire:model.live.blur syncs ephemeral immediate, network on blur
- wire:model.blur.live syncs both on blur
- Supports .blur, .change, .enter and combinations
Migration: Replace wire:model.blur with wire:model.live.blur for old behavior.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
```
**PR Title:**
`feat(wire:model)!: control ephemeral sync timing with modifiers`
**PR Description:**
```
## Summary
- Modifiers before `.live` control ephemeral (x-model) sync timing
- Modifiers after `.live` control network timing
- BREAKING: `wire:model.blur` now delays ephemeral sync, use `.live.blur` for old behavior
## Test plan
- [ ] `wire:model.blur` delays ephemeral sync until blur
- [ ] `wire:model.live.blur` matches old `.blur` behavior
- [ ] `wire:model.blur.live` delays both ephemeral and network until blur
- [ ] Compound modifiers work (`.blur.enter`)
- [ ] Debounce/throttle work on network layer
```

59
vendor/livewire/livewire/README.md vendored Normal file
View file

@ -0,0 +1,59 @@
<p align="center"><img width="300" src="/art/logo.svg" alt="Livewire Logo"></p>
<p align="center">
<a href="https://packagist.org/packages/livewire/livewire">
<img src="https://poser.pugx.org/livewire/livewire/d/total.svg" alt="Total Downloads">
</a>
<a href="https://packagist.org/packages/livewire/livewire">
<img src="https://poser.pugx.org/livewire/livewire/v/stable.svg" alt="Latest Stable Version">
</a>
<a href="https://packagist.org/packages/livewire/livewire">
<img src="https://poser.pugx.org/livewire/livewire/license.svg" alt="License">
</a>
</p>
## Introduction
Livewire is a full-stack framework for Laravel that allows you to build dynamic UI components without leaving PHP.
## Official Documentation
You can read the official documentation on the [Livewire website](https://livewire.laravel.com/docs).
## Local Development
```bash
git clone git@github.com:livewire/livewire.git && cd livewire
composer setup
```
This installs PHP and JS dependencies and sets up ChromeDriver for browser tests.
```bash
composer test:unit # unit tests
composer test:browser # browser tests (headless)
composer test:browser:headed # browser tests (opens Chrome)
composer test:browser -- --filter="SupportCSP" # specific tests
```
To build the JS assets after making changes: `npm run build`
## Contributing
<a name="contributing"></a>
Thank you for considering contributing to Livewire! You can read the contribution guide [here](.github/CONTRIBUTING.md).
## Code of Conduct
<a name="code-of-conduct"></a>
In order to ensure that the Laravel community is welcoming to all, please review and abide by Laravel's [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
## Security Vulnerabilities
<a name="security-vulnerabilities"></a>
Please review [our security policy](https://github.com/livewire/livewire/security/policy) on how to report security vulnerabilities.
## License
<a name="license"></a>
Livewire is open-sourced software licensed under the [MIT license](LICENSE.md).

70
vendor/livewire/livewire/composer.json vendored Normal file
View file

@ -0,0 +1,70 @@
{
"name": "livewire/livewire",
"description": "A front-end framework for Laravel.",
"license": "MIT",
"authors": [
{
"name": "Caleb Porzio",
"email": "calebporzio@gmail.com"
}
],
"require": {
"php": "^8.1",
"illuminate/database": "^10.0|^11.0|^12.0|^13.0",
"illuminate/routing": "^10.0|^11.0|^12.0|^13.0",
"illuminate/support": "^10.0|^11.0|^12.0|^13.0",
"illuminate/validation": "^10.0|^11.0|^12.0|^13.0",
"league/mime-type-detection": "^1.9",
"symfony/console": "^6.0|^7.0|^8.0",
"symfony/http-kernel": "^6.2|^7.0|^8.0",
"laravel/prompts": "^0.1.24|^0.2|^0.3"
},
"require-dev": {
"psy/psysh": "^0.11.22|^0.12",
"mockery/mockery": "^1.3.1",
"phpunit/phpunit": "^10.4|^11.5|^12.5",
"laravel/framework": "^10.15.0|^11.0|^12.0|^13.0",
"orchestra/testbench": "^8.21.0|^9.0|^10.0|^11.0",
"orchestra/testbench-dusk": "^8.24|^9.1|^10.0|^11.0",
"calebporzio/sushi": "^2.1"
},
"autoload": {
"files": [
"src/helpers.php"
],
"psr-4": {
"Livewire\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"App\\": "vendor/orchestra/testbench-core/laravel/app",
"Tests\\": "tests/",
"LegacyTests\\": "legacy_tests/"
}
},
"extra": {
"laravel": {
"providers": [
"Livewire\\LivewireServiceProvider"
],
"aliases": {
"Livewire": "Livewire\\Livewire"
}
}
},
"scripts": {
"setup": [
"@composer install",
"npm install",
"@php vendor/bin/dusk-updater detect --auto-update --no-interaction",
"npm run build"
],
"test": "phpunit --configuration phpunit.xml.dist",
"test:unit": "phpunit --configuration phpunit.xml.dist --testsuite Unit",
"test:browser": "phpunit --configuration phpunit.xml.dist --testsuite Browser",
"test:browser:headed": "DUSK_HEADLESS_DISABLED=true phpunit --configuration phpunit.xml.dist --testsuite Browser"
},
"minimum-stability": "dev",
"prefer-stable": true
}

View file

@ -0,0 +1,282 @@
<?php
return [
/*
|---------------------------------------------------------------------------
| Component Locations
|---------------------------------------------------------------------------
|
| This value sets the root directories that'll be used to resolve view-based
| components like single and multi-file components. The make command will
| use the first directory in this array to add new component files to.
|
*/
'component_locations' => [
resource_path('views/components'),
resource_path('views/livewire'),
],
/*
|---------------------------------------------------------------------------
| Component Namespaces
|---------------------------------------------------------------------------
|
| This value sets default namespaces that will be used to resolve view-based
| components like single-file and multi-file components. These folders'll
| also be referenced when creating new components via the make command.
|
*/
'component_namespaces' => [
'layouts' => resource_path('views/layouts'),
'pages' => resource_path('views/pages'),
],
/*
|---------------------------------------------------------------------------
| Page Layout
|---------------------------------------------------------------------------
| The view that will be used as the layout when rendering a single component as
| an entire page via `Route::livewire('/post/create', 'pages::create-post')`.
| In this case, the content of pages::create-post will render into $slot.
|
*/
'component_layout' => 'layouts::app',
/*
|---------------------------------------------------------------------------
| Lazy Loading Placeholder
|---------------------------------------------------------------------------
| Livewire allows you to lazy load components that would otherwise slow down
| the initial page load. Every component can have a custom placeholder or
| you can define the default placeholder view for all components below.
|
*/
'component_placeholder' => null, // Example: 'placeholders::skeleton'
/*
|---------------------------------------------------------------------------
| Make Command
|---------------------------------------------------------------------------
| This value determines the default configuration for the artisan make command
| You can configure the component type (sfc, mfc, class) and whether to use
| the high-voltage (⚡) emoji as a prefix in the sfc|mfc component names.
|
*/
'make_command' => [
'type' => 'sfc', // Options: 'sfc', 'mfc', 'class'
'emoji' => true, // Options: true, false
'with' => [
'js' => false,
'css' => false,
'test' => false,
],
],
/*
|---------------------------------------------------------------------------
| Class Namespace
|---------------------------------------------------------------------------
|
| This value sets the root class namespace for Livewire component classes in
| your application. This value will change where component auto-discovery
| finds components. It's also referenced by the file creation commands.
|
*/
'class_namespace' => 'App\\Livewire',
/*
|---------------------------------------------------------------------------
| Class Path
|---------------------------------------------------------------------------
|
| This value is used to specify the path where Livewire component class files
| are created when running creation commands like `artisan make:livewire`.
| This path is customizable to match your projects directory structure.
|
*/
'class_path' => app_path('Livewire'),
/*
|---------------------------------------------------------------------------
| View Path
|---------------------------------------------------------------------------
|
| This value is used to specify where Livewire component Blade templates are
| stored when running file creation commands like `artisan make:livewire`.
| It is also used if you choose to omit a component's render() method.
|
*/
'view_path' => resource_path('views/livewire'),
/*
|---------------------------------------------------------------------------
| Temporary File Uploads
|---------------------------------------------------------------------------
|
| Livewire handles file uploads by storing uploads in a temporary directory
| before the file is stored permanently. All file uploads are directed to
| a global endpoint for temporary storage. You may configure this below:
|
*/
'temporary_file_upload' => [
'disk' => env('LIVEWIRE_TEMPORARY_FILE_UPLOAD_DISK'), // Example: 'local', 's3' | Default: 'default'
'rules' => null, // Example: ['file', 'mimes:png,jpg'] | Default: ['required', 'file', 'max:12288'] (12MB)
'directory' => null, // Example: 'tmp' | Default: 'livewire-tmp'
'middleware' => null, // Example: 'throttle:5,1' | Default: 'throttle:60,1'
'preview_mimes' => [ // Supported file types for temporary pre-signed file URLs...
'png', 'gif', 'bmp', 'svg', 'wav', 'mp4',
'mov', 'avi', 'wmv', 'mp3', 'm4a',
'jpg', 'jpeg', 'mpga', 'webp', 'wma',
],
'max_upload_time' => 5, // Max duration (in minutes) before an upload is invalidated...
'cleanup' => true, // Should cleanup temporary uploads older than 24 hrs...
],
/*
|---------------------------------------------------------------------------
| Render On Redirect
|---------------------------------------------------------------------------
|
| This value determines if Livewire will run a component's `render()` method
| after a redirect has been triggered using something like `redirect(...)`
| Setting this to true will render the view once more before redirecting
|
*/
'render_on_redirect' => false,
/*
|---------------------------------------------------------------------------
| Eloquent Model Binding
|---------------------------------------------------------------------------
|
| Previous versions of Livewire supported binding directly to eloquent model
| properties using wire:model by default. However, this behavior has been
| deemed too "magical" and has therefore been put under a feature flag.
|
*/
'legacy_model_binding' => false,
/*
|---------------------------------------------------------------------------
| Auto-inject Frontend Assets
|---------------------------------------------------------------------------
|
| By default, Livewire automatically injects its JavaScript and CSS into the
| <head> and <body> of pages containing Livewire components. By disabling
| this behavior, you need to use @livewireStyles and @livewireScripts.
|
*/
'inject_assets' => true,
/*
|---------------------------------------------------------------------------
| Navigate (SPA mode)
|---------------------------------------------------------------------------
|
| By adding `wire:navigate` to links in your Livewire application, Livewire
| will prevent the default link handling and instead request those pages
| via AJAX, creating an SPA-like effect. Configure this behavior here.
|
*/
'navigate' => [
'show_progress_bar' => true,
'progress_bar_color' => '#2299dd',
],
/*
|---------------------------------------------------------------------------
| HTML Morph Markers
|---------------------------------------------------------------------------
|
| Livewire intelligently "morphs" existing HTML into the newly rendered HTML
| after each update. To make this process more reliable, Livewire injects
| "markers" into the rendered Blade surrounding @if, @class & @foreach.
|
*/
'inject_morph_markers' => true,
/*
|---------------------------------------------------------------------------
| Smart Wire Keys
|---------------------------------------------------------------------------
|
| Livewire uses loops and keys used within loops to generate smart keys that
| are applied to nested components that don't have them. This makes using
| nested components more reliable by ensuring that they all have keys.
|
*/
'smart_wire_keys' => true,
/*
|---------------------------------------------------------------------------
| Pagination Theme
|---------------------------------------------------------------------------
|
| When enabling Livewire's pagination feature by using the `WithPagination`
| trait, Livewire will use Tailwind templates to render pagination views
| on the page. If you want Bootstrap CSS, you can specify: "bootstrap"
|
*/
'pagination_theme' => 'tailwind',
/*
|---------------------------------------------------------------------------
| Release Token
|---------------------------------------------------------------------------
|
| This token is stored client-side and sent along with each request to check
| a users session to see if a new release has invalidated it. If there is
| a mismatch it will throw an error and prompt for a browser refresh.
|
*/
'release_token' => 'a',
/*
|---------------------------------------------------------------------------
| CSP Safe
|---------------------------------------------------------------------------
|
| This config is used to determine if Livewire will use the CSP-safe version
| of Alpine in its bundle. This is useful for applications that are using
| strict Content Security Policy (CSP) to protect against XSS attacks.
|
*/
'csp_safe' => false,
/*
|---------------------------------------------------------------------------
| Payload Guards
|---------------------------------------------------------------------------
|
| These settings protect against malicious or oversized payloads that could
| cause denial of service. The default values should feel reasonable for
| most web applications. Each can be set to null to disable the limit.
|
*/
'payload' => [
'max_size' => 1024 * 1024, // 1MB - maximum request payload size in bytes
'max_nesting_depth' => 10, // Maximum depth of dot-notation property paths
'max_calls' => 50, // Maximum method calls per request
'max_components' => 200, // Maximum components per batch request
],
];

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

17543
vendor/livewire/livewire/dist/livewire.js vendored Normal file

File diff suppressed because it is too large Load diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,2 @@
{"/livewire.js":"0ae8dee3"}

View file

@ -0,0 +1,10 @@
<?php
namespace Livewire;
use Livewire\Features\SupportAttributes\Attribute as BaseAttribute;
abstract class Attribute extends BaseAttribute
{
//
}

View file

@ -0,0 +1,11 @@
<?php
namespace Livewire\Attributes;
use Livewire\Features\SupportAsync\BaseAsync;
#[\Attribute]
class Async extends BaseAsync
{
//
}

View file

@ -0,0 +1,12 @@
<?php
namespace Livewire\Attributes;
use Attribute;
use Livewire\Features\SupportAuthorization\BaseAuthorize;
#[Attribute(Attribute::IS_REPEATABLE | Attribute::TARGET_METHOD)]
class Authorize extends BaseAuthorize
{
//
}

View file

@ -0,0 +1,11 @@
<?php
namespace Livewire\Attributes;
use Livewire\Features\SupportComputed\BaseComputed;
#[\Attribute]
class Computed extends BaseComputed
{
//
}

View file

@ -0,0 +1,11 @@
<?php
namespace Livewire\Attributes;
use Livewire\Features\SupportLazyLoading\BaseDefer;
#[\Attribute]
class Defer extends BaseDefer
{
//
}

View file

@ -0,0 +1,11 @@
<?php
namespace Livewire\Attributes;
use Livewire\Features\SupportIsolating\BaseIsolate;
#[\Attribute]
class Isolate extends BaseIsolate
{
//
}

View file

@ -0,0 +1,11 @@
<?php
namespace Livewire\Attributes;
use Livewire\Features\SupportJsEvaluation\BaseJs;
#[\Attribute]
class Js extends BaseJs
{
//
}

View file

@ -0,0 +1,11 @@
<?php
namespace Livewire\Attributes;
use Livewire\Features\SupportJson\BaseJson;
#[\Attribute(\Attribute::TARGET_METHOD)]
class Json extends BaseJson
{
//
}

View file

@ -0,0 +1,11 @@
<?php
namespace Livewire\Attributes;
use Livewire\Features\SupportPageComponents\BaseLayout;
#[\Attribute]
class Layout extends BaseLayout
{
//
}

View file

@ -0,0 +1,11 @@
<?php
namespace Livewire\Attributes;
use Livewire\Features\SupportLazyLoading\BaseLazy;
#[\Attribute]
class Lazy extends BaseLazy
{
//
}

View file

@ -0,0 +1,11 @@
<?php
namespace Livewire\Attributes;
use Livewire\Features\SupportLockedProperties\BaseLocked;
#[\Attribute]
class Locked extends BaseLocked
{
//
}

View file

@ -0,0 +1,11 @@
<?php
namespace Livewire\Attributes;
use Livewire\Features\SupportWireModelingNestedComponents\BaseModelable;
#[\Attribute]
class Modelable extends BaseModelable
{
//
}

View file

@ -0,0 +1,12 @@
<?php
namespace Livewire\Attributes;
use Attribute;
use Livewire\Features\SupportEvents\BaseOn;
#[Attribute(Attribute::IS_REPEATABLE | Attribute::TARGET_CLASS | Attribute::TARGET_METHOD)]
class On extends BaseOn
{
//
}

View file

@ -0,0 +1,11 @@
<?php
namespace Livewire\Attributes;
use Livewire\Features\SupportReactiveProps\BaseReactive;
#[\Attribute]
class Reactive extends BaseReactive
{
//
}

View file

@ -0,0 +1,11 @@
<?php
namespace Livewire\Attributes;
use Livewire\Features\SupportRenderless\BaseRenderless;
#[\Attribute]
class Renderless extends BaseRenderless
{
//
}

View file

@ -0,0 +1,13 @@
<?php
namespace Livewire\Attributes;
use Attribute;
use Livewire\Features\SupportValidation\BaseRule;
#[Attribute(Attribute::IS_REPEATABLE | Attribute::TARGET_ALL)]
class Rule extends BaseRule
{
//
}

View file

@ -0,0 +1,12 @@
<?php
namespace Livewire\Attributes;
use Attribute;
use Livewire\Features\SupportSession\BaseSession;
#[Attribute(Attribute::TARGET_PROPERTY)]
class Session extends BaseSession
{
//
}

View file

@ -0,0 +1,11 @@
<?php
namespace Livewire\Attributes;
use Livewire\Features\SupportPageComponents\BaseTitle;
#[\Attribute]
class Title extends BaseTitle
{
//
}

View file

@ -0,0 +1,11 @@
<?php
namespace Livewire\Attributes;
use Livewire\Features\SupportTransitions\BaseTransitionAttribute;
#[\Attribute(\Attribute::TARGET_METHOD)]
class Transition extends BaseTransitionAttribute
{
//
}

View file

@ -0,0 +1,11 @@
<?php
namespace Livewire\Attributes;
use Livewire\Features\SupportQueryString\BaseUrl;
#[\Attribute]
class Url extends BaseUrl
{
//
}

View file

@ -0,0 +1,13 @@
<?php
namespace Livewire\Attributes;
use Attribute;
use Livewire\Features\SupportValidation\BaseValidate;
#[Attribute(Attribute::IS_REPEATABLE | Attribute::TARGET_ALL)]
class Validate extends BaseValidate
{
//
}

View file

@ -0,0 +1,247 @@
<?php
namespace Livewire\Compiler;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
class CacheManager
{
public function __construct(
public string $cacheDirectory,
) {}
public function hasBeenCompiled(string $sourcePath): bool
{
$classPath = $this->getClassPath($sourcePath);
return file_exists($classPath);
}
public function isExpired(string $sourcePath): bool
{
$sourceModificationTime = $this->getLatestFileModificationTimeOfSource($sourcePath);
$compiledModificationTime = $this->getLatestFileModificationTimeOfCompiledFiles($sourcePath);
return $sourceModificationTime > $compiledModificationTime;
}
public function getLatestFileModificationTimeOfSource(string $sourcePath): int
{
if (is_dir($sourcePath)) {
return max(array_map('filemtime', glob($sourcePath . '/*')));
}
return filemtime($sourcePath);
}
public function getLatestFileModificationTimeOfCompiledFiles(string $sourcePath): int
{
$classPath = $this->getClassPath($sourcePath);
$viewPath = $this->getViewPath($sourcePath);
$scriptPath = $this->getScriptPath($sourcePath);
$stylePath = $this->getStylePath($sourcePath);
$globalStylePath = $this->getGlobalStylePath($sourcePath);
$times = [];
foreach ([$classPath, $viewPath, $scriptPath, $stylePath, $globalStylePath] as $path) {
if (file_exists($path)) {
$times[] = filemtime($path);
}
}
return empty($times) ? 0 : min($times);
}
public function getClassName(string $sourcePath): string
{
$instance = require $this->getClassPath($sourcePath);
return $instance::class;
}
public function getHash(string $sourcePath): string
{
return substr(md5(Str::after($sourcePath, base_path())), 0, 8);
}
public function getClassPath(string $sourcePath): string
{
$hash = $this->getHash($sourcePath);
return $this->cacheDirectory . '/classes/' . $hash . '.php';
}
public function getViewPath(string $sourcePath): string
{
$hash = $this->getHash($sourcePath);
return $this->cacheDirectory . '/views/' . $hash . '.blade.php';
}
public function getScriptPath(string $sourcePath): string
{
$hash = $this->getHash($sourcePath);
return $this->cacheDirectory . '/scripts/' . $hash . '.js';
}
public function getStylePath(string $sourcePath): string
{
$hash = $this->getHash($sourcePath);
return $this->cacheDirectory . '/styles/' . $hash . '.css';
}
public function getGlobalStylePath(string $sourcePath): string
{
$hash = $this->getHash($sourcePath);
return $this->cacheDirectory . '/styles/' . $hash . '.global.css';
}
public function getPlaceholderPath(string $sourcePath): string
{
$hash = $this->getHash($sourcePath);
return $this->cacheDirectory . '/placeholders/' . $hash . '.blade.php';
}
public function writeClassFile(string $sourcePath, string $contents): void
{
$this->invalidateOpCache($sourcePath);
$classPath = $this->getClassPath($sourcePath);
$this->ensureCacheDirectoryExists();
File::makeDirectory($this->cacheDirectory . '/classes', 0777, true, true);
// Use atomic write to prevent race conditions when multiple
// concurrent requests try to compile the same component.
File::replace($classPath, $contents);
}
public function writeViewFile(string $sourcePath, string $contents): void
{
$viewPath = $this->getViewPath($sourcePath);
$this->ensureCacheDirectoryExists();
File::makeDirectory($this->cacheDirectory . '/views', 0777, true, true);
File::replace($viewPath, $contents);
$this->prepareGeneratedFileForCompilation($viewPath);
}
public function writeScriptFile(string $sourcePath, string $contents): void
{
$scriptPath = $this->getScriptPath($sourcePath);
$this->ensureCacheDirectoryExists();
File::makeDirectory($this->cacheDirectory . '/scripts', 0777, true, true);
File::replace($scriptPath, $contents);
}
public function writeStyleFile(string $sourcePath, string $contents): void
{
$stylePath = $this->getStylePath($sourcePath);
$this->ensureCacheDirectoryExists();
File::makeDirectory($this->cacheDirectory . '/styles', 0777, true, true);
File::replace($stylePath, $contents);
}
public function writeGlobalStyleFile(string $sourcePath, string $contents): void
{
$stylePath = $this->getGlobalStylePath($sourcePath);
$this->ensureCacheDirectoryExists();
File::makeDirectory($this->cacheDirectory . '/styles', 0777, true, true);
File::replace($stylePath, $contents);
}
public function writePlaceholderFile(string $sourcePath, string $contents): void
{
$placeholderPath = $this->getPlaceholderPath($sourcePath);
$this->ensureCacheDirectoryExists();
File::makeDirectory($this->cacheDirectory . '/placeholders', 0777, true, true);
File::replace($placeholderPath, $contents);
$this->prepareGeneratedFileForCompilation($placeholderPath);
}
public function writeIslandFile(string $sourcePath, string $contents): void
{
$viewPath = $this->getViewPath($sourcePath);
$this->ensureCacheDirectoryExists();
File::makeDirectory($this->cacheDirectory . '/views', 0777, true, true);
File::replace($viewPath, $contents);
$this->prepareGeneratedFileForCompilation($viewPath);
}
public function invalidateOpCache(string $sourcePath): void
{
// Prevent error in case if `opcache.restrict_api` directive is set
if (function_exists('opcache_invalidate') && strlen(ini_get('opcache.restrict_api')) < 1) {
opcache_invalidate($sourcePath, true);
}
}
protected function ensureCacheDirectoryExists(): void
{
File::makeDirectory($this->cacheDirectory, 0777, true, true);
$gitignorePath = $this->cacheDirectory . '/.gitignore';
if (! file_exists($gitignorePath)) {
try {
File::put($gitignorePath, "*\n!.gitignore");
} catch (\Throwable) {
// Non-critical, ignore if another process created it
}
}
}
public function prepareGeneratedFileForCompilation(string $path): void
{
// This is a fix for a gnarly issue: blade's compiler uses filemtimes to determine if a compiled view has become expired.
// AND it's comparison includes equals like this: $path >= $cachedPath
// AND file_put_contents won't update the filemtime if the contents are the same
// THEREFORE because we are creating a blade file at the same "second" that it is compiled
// both the source file and the cached file's filemtime's match, therefore it become's in a perpetual state
// of always being expired. So we mutate the source file to be one second behind so that the cached
// view file is one second ahead. Phew. this one took a minute to find lol.
$original = filemtime($path);
touch($path, $original - 1);
// But because of this, if a file is compiled and then saved again within the same second,
// it will not get recompiled because it will look like the source was created 1 second
// before the compiled file, not passing the $path >= $cachedPath check and skipping
// compilation. To force recompilation we need to delete the compiled file first.
File::delete(app('blade.compiler')->getCompiledPath($path));
}
public function clearCompiledFiles($output = null): void
{
try {
if (is_dir($this->cacheDirectory)) {
File::deleteDirectory($this->cacheDirectory);
}
} catch (\Exception $e) {
// Silently fail to avoid breaking view:clear if there's an issue
// But we can log it if output is available
if ($output && method_exists($output, 'writeln')) {
$output->writeln("<comment>Note: Could not clear Livewire compiled files.</comment>");
}
}
}
}

View file

@ -0,0 +1,106 @@
<?php
namespace Livewire\Compiler;
use Livewire\Compiler\Parser\SingleFileParser;
use Livewire\Compiler\Parser\MultiFileParser;
class Compiler
{
protected $prepareViewsForCompilationUsing = [];
public function __construct(
public CacheManager $cacheManager,
) {}
public function compile(string $path): string
{
if (! file_exists($path)) {
throw new \Exception("File not found: [{$path}]");
}
if (
(! $this->cacheManager->hasBeenCompiled($path))
|| $this->cacheManager->isExpired($path)
) {
$this->compilePath($path);
}
return $this->cacheManager->getClassName($path);
}
public function compilePath(string $path): void
{
$parser = is_file($path)
? SingleFileParser::parse($this, $path)
: MultiFileParser::parse($this, $path);
$viewFileName = $this->cacheManager->getViewPath($path);
$placeholderFileName = null;
$scriptFileName = null;
$styleFileName = null;
$globalStyleFileName = null;
$placeholderContents = $parser->generatePlaceholderContents();
$scriptContents = $parser->generateScriptContents();
$styleContents = $parser->generateStyleContents();
$globalStyleContents = $parser->generateGlobalStyleContents();
if ($placeholderContents !== null) {
$placeholderFileName = $this->cacheManager->getPlaceholderPath($path);
$this->cacheManager->writePlaceholderFile($path, $placeholderContents);
}
if ($scriptContents !== null) {
$scriptFileName = $this->cacheManager->getScriptPath($path);
$this->cacheManager->writeScriptFile($path, $scriptContents);
}
if ($styleContents !== null) {
$styleFileName = $this->cacheManager->getStylePath($path);
$this->cacheManager->writeStyleFile($path, $styleContents);
}
if ($globalStyleContents !== null) {
$globalStyleFileName = $this->cacheManager->getGlobalStylePath($path);
$this->cacheManager->writeGlobalStyleFile($path, $globalStyleContents);
}
$this->cacheManager->writeViewFile($path, $parser->generateViewContents());
// Ensure the class file is the last write, as it's used
// in the hasBeenCompiled() check, so its presence on
// disk means everything has been compiled...
$this->cacheManager->writeClassFile($path, $parser->generateClassContents(
$viewFileName,
$placeholderFileName,
$scriptFileName,
$styleFileName,
$globalStyleFileName,
));
}
public function clearCompiled($output = null)
{
$this->cacheManager->clearCompiledFiles($output);
}
public function prepareViewsForCompilationUsing($callback)
{
$this->prepareViewsForCompilationUsing[] = $callback;
}
public function prepareViewForCompilation($contents, $path)
{
foreach ($this->prepareViewsForCompilationUsing as $callback) {
$contents = $callback($contents, $path);
}
return $contents;
}
}

View file

@ -0,0 +1,239 @@
<?php
namespace Livewire\Compiler\Parser;
use Livewire\Compiler\Compiler;
class MultiFileParser extends Parser
{
public function __construct(
public string $path,
public ?string $scriptPortion,
public ?string $stylePortion,
public ?string $globalStylePortion,
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';
$stylePath = $path . '/' . $name . '.css';
$globalStylePath = $path . '/' . $name . '.global.css';
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;
$stylePortion = file_exists($stylePath) ? file_get_contents($stylePath) : null;
$globalStylePortion = file_exists($globalStylePath) ? file_get_contents($globalStylePath) : null;
$classPortion = file_get_contents($classPath);
$viewPortion = $compiler->prepareViewForCompilation(file_get_contents($viewPath), $viewPath);
$placeholderPortion = static::extractPlaceholderPortion($viewPortion);
return new self(
$path,
$scriptPortion,
$stylePortion,
$globalStylePortion,
$classPortion,
$viewPortion,
$placeholderPortion,
);
}
public function generateClassContents(?string $viewFileName = null, ?string $placeholderFileName = null, ?string $scriptFileName = null, ?string $styleFileName = null, ?string $globalStyleFileName = 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);
}
if ($styleFileName) {
$classContents = $this->injectStyleMethod($classContents, $styleFileName);
}
if ($globalStyleFileName) {
$classContents = $this->injectGlobalStyleMethod($classContents, $globalStyleFileName);
}
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);
// Hoist imports to the top
$imports = [];
$scriptContents = preg_replace_callback(
'/^import\s+.+?;?\s*$/m',
function ($matches) use (&$imports) {
$imports[] = trim($matches[0]);
return '';
},
$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 generateStyleContents(): ?string
{
if ($this->stylePortion === null || trim($this->stylePortion) === '') {
return null;
}
return trim($this->stylePortion);
}
public function generateGlobalStyleContents(): ?string
{
if ($this->globalStylePortion === null || trim($this->globalStylePortion) === '') {
return null;
}
return trim($this->globalStylePortion);
}
/**
* 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>";
}
// Add style section if present
if ($this->stylePortion !== null && trim($this->stylePortion) !== '') {
$indentedStyle = $this->addCssIndentation(trim($this->stylePortion));
$sfcContents .= "\n\n<style>\n" . $indentedStyle . "\n</style>";
}
// Add global style section if present
if ($this->globalStylePortion !== null && trim($this->globalStylePortion) !== '') {
$indentedGlobalStyle = $this->addCssIndentation(trim($this->globalStylePortion));
$sfcContents .= "\n\n<style global>\n" . $indentedGlobalStyle . "\n</style>";
}
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);
}
protected function addCssIndentation(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);
}
}

View file

@ -0,0 +1,235 @@
<?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) {
// Use brackets around the number to prevent substring matching issues
// e.g. "ISLANDREPLACEMENT:[1]" won't match as part of "ISLANDREPLACEMENT:[10]"
$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
{
// Use (*SKIP)(*FAIL) to ignore "new" inside comments...
$skipComments = '(?:\/\/[^\n]*|\/\*.*?\*\/)(*SKIP)(*FAIL)';
// Find the position of the first "new" outside of comments...
if (preg_match('/' . $skipComments . '|\bnew\b/s', $contents, $newMatch, PREG_OFFSET_CAPTURE)) {
$newPosition = $newMatch[0][1];
// Check if "return new" exists outside of comments and find where "new" starts in that match...
$hasReturnNew = preg_match('/' . $skipComments . '|\breturn\s+(new\b)/s', $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
{
// Use (*SKIP)(*FAIL) to ignore "new" inside comments...
$skipComments = '(?:\/\/[^\n]*|\/\*.*?\*\/)(*SKIP)(*FAIL)';
if (!preg_match('/' . $skipComments . '|\bnew\b/s', $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 injectStyleMethod(string $contents, string $styleFileName): 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 styleModuleSrc()
{
return '{$styleFileName}';
}
}
PHP
, $position, 1);
}
return $contents;
}
protected function injectGlobalStyleMethod(string $contents, string $globalStyleFileName): 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 globalStyleModuleSrc()
{
return '{$globalStyleFileName}';
}
}
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)) {
$useStatements = static::extractUseStatements($matches[1]);
}
// 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;
}
public static function extractUseStatements(string $contents): ?string
{
// Use (*SKIP)(*FAIL) to ignore "use" statements inside comments...
$skipComments = '(?:\/\/[^\n]*|\/\*.*?\*\/)(*SKIP)(*FAIL)';
// Extract all use statements (excluding closure `use (...)` clauses)...
if (! preg_match_all('/' . $skipComments . '|\buse\s+[^;()]+;/s', $contents, $useMatches)) {
return null;
}
return $useMatches[0] ? implode("\n", $useMatches[0]) : null;
}
}

View file

@ -0,0 +1,420 @@
<?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 $stylePortion,
public ?string $globalStylePortion,
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);
$stylePortion = static::extractStylePortion($mutableContents);
$globalStylePortion = static::extractGlobalStylePortion($mutableContents);
$classPortion = static::extractClassPortion($mutableContents);
$placeholderPortion = static::extractPlaceholderPortion($mutableContents);
$viewPortion = trim($mutableContents);
return new self(
$path,
$contents,
$scriptPortion,
$stylePortion,
$globalStylePortion,
$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);
// Remove @verbatim/@endverbatim blocks (content inside is literal, not extractable)
$viewContents = preg_replace('/@verbatim\s*.*?@endverbatim/s', '', $viewContents);
// Only match script tags at column 0 (root-level). Nested scripts are indented and should stay in the view.
$pattern = '/(?:^|\n)(<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;
}
public static function extractStylePortion(string &$contents): ?string
{
// Get the view portion (everything after the PHP class)
$viewContents = static::getViewPortion($contents);
// Remove @verbatim/@endverbatim blocks (content inside is literal, not extractable)
$viewContents = preg_replace('/@verbatim\s*.*?@endverbatim/s', '', $viewContents);
// Only match style tags at column 0 (root-level), excluding <style global>
$pattern = '/(?:^|\n)(<style\b(?![^>]*\bglobal\b)[^>]*>.*?<\/style>)/s';
preg_match_all($pattern, $viewContents, $matches);
if (empty($matches[1])) {
return null;
}
// Take the last style tag (most likely to be at root level)
$styleTag = end($matches[1]);
// Remove it from the original contents
$contents = str_replace($styleTag, '', $contents);
return $styleTag;
}
public static function extractGlobalStylePortion(string &$contents): ?string
{
// Get the view portion (everything after the PHP class)
$viewContents = static::getViewPortion($contents);
// Remove @verbatim/@endverbatim blocks (content inside is literal, not extractable)
$viewContents = preg_replace('/@verbatim\s*.*?@endverbatim/s', '', $viewContents);
// Only match style tags with "global" attribute at column 0 (root-level)
$pattern = '/(?:^|\n)(<style\b[^>]*\bglobal\b[^>]*>.*?<\/style>)/s';
preg_match_all($pattern, $viewContents, $matches);
if (empty($matches[1])) {
return null;
}
// Take the last global style tag
$styleTag = end($matches[1]);
// Remove it from the original contents
$contents = str_replace($styleTag, '', $contents);
return $styleTag;
}
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 $styleFileName = null, ?string $globalStyleFileName = 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);
}
if ($styleFileName) {
$classContents = $this->injectStyleMethod($classContents, $styleFileName);
}
if ($globalStyleFileName) {
$classContents = $this->injectGlobalStyleMethod($classContents, $globalStyleFileName);
}
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);
}
public function generateStyleContents(): ?string
{
if ($this->stylePortion === null) return null;
$pattern = '/<style\b[^>]*>(.*?)<\/style>/s';
if (preg_match($pattern, $this->stylePortion, $matches)) {
return trim($matches[1]);
}
return null;
}
public function generateGlobalStyleContents(): ?string
{
if ($this->globalStylePortion === null) return null;
$pattern = '/<style\b[^>]*>(.*?)<\/style>/s';
if (preg_match($pattern, $this->globalStylePortion, $matches)) {
return trim($matches[1]);
}
return null;
}
public function generateStyleContentsForMultiFile(): ?string
{
if ($this->stylePortion === null) return null;
$styleContents = '';
$pattern = '/<style\b[^>]*>(.*?)<\/style>/s';
if (preg_match($pattern, $this->stylePortion, $matches)) {
$styleContents = $matches[1];
}
return $this->cleanupCssIndentation($styleContents);
}
public function generateGlobalStyleContentsForMultiFile(): ?string
{
if ($this->globalStylePortion === null) return null;
$styleContents = '';
$pattern = '/<style\b[^>]*>(.*?)<\/style>/s';
if (preg_match($pattern, $this->globalStylePortion, $matches)) {
$styleContents = $matches[1];
}
return $this->cleanupCssIndentation($styleContents);
}
protected function cleanupCssIndentation(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);
}
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);
}
}

View file

@ -0,0 +1,169 @@
<?php
namespace Livewire;
use Livewire\Features\SupportValidation\HandlesValidation;
use Livewire\Features\SupportTransitions\HandlesTransitions;
use Livewire\Features\SupportStreaming\HandlesStreaming;
use Livewire\Features\SupportSlots\HandlesSlots;
use Livewire\Features\SupportReleaseTokens\HandlesReleaseTokens;
use Livewire\Features\SupportRedirects\HandlesRedirects;
use Livewire\Features\SupportPageComponents\HandlesPageComponents;
use Livewire\Features\SupportJsEvaluation\HandlesJsEvaluation;
use Livewire\Features\SupportIslands\HandlesIslands;
use Livewire\Features\SupportFormObjects\HandlesFormObjects;
use Livewire\Features\SupportEvents\HandlesEvents;
use Livewire\Features\SupportHtmlAttributeForwarding\HandlesHtmlAttributeForwarding;
use Livewire\Features\SupportDisablingBackButtonCache\HandlesDisablingBackButtonCache;
use Livewire\Features\SupportAttributes\HandlesAttributes;
use Livewire\Features\SupportRenderless\HandlesRenderless;
use Livewire\Exceptions\PropertyNotFoundException;
use Livewire\Concerns\InteractsWithProperties;
use Illuminate\Support\Traits\Macroable;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use BadMethodCallException;
abstract class Component
{
use Macroable { __call as macroCall; }
use AuthorizesRequests;
use InteractsWithProperties;
use HandlesEvents;
use HandlesIslands;
use HandlesRedirects;
use HandlesTransitions;
use HandlesStreaming;
use HandlesAttributes;
use HandlesValidation;
use HandlesFormObjects;
use HandlesJsEvaluation;
use HandlesReleaseTokens;
use HandlesPageComponents;
use HandlesDisablingBackButtonCache;
use HandlesSlots;
use HandlesHtmlAttributeForwarding;
use HandlesRenderless;
protected $__id;
protected $__name;
function id()
{
return $this->getId();
}
function setId($id)
{
$this->__id = $id;
}
function getId()
{
return $this->__id;
}
function setName($name)
{
$this->__name = $name;
}
function getName()
{
return $this->__name;
}
function forceRender()
{
store($this)->set('forceRender', true);
}
function skipMount()
{
store($this)->set('skipMount', true);
}
function skipHydrate()
{
store($this)->set('skipHydrate', true);
}
function hasProvidedView()
{
return method_exists($this, 'view');
}
function getProvidedView()
{
return $this->view();
}
function __isset($property)
{
try {
$value = $this->__get($property);
if (isset($value)) {
return true;
}
} catch(PropertyNotFoundException $ex) {}
return false;
}
function __get($property)
{
$value = 'noneset';
$returnValue = function ($newValue) use (&$value) {
$value = $newValue;
};
$finish = trigger('__get', $this, $property, $returnValue);
$value = $finish($value);
if ($value === 'noneset') {
throw new PropertyNotFoundException($property, $this->getName());
}
return $value;
}
function __unset($property)
{
trigger('__unset', $this, $property);
}
function __call($method, $params)
{
$value = 'noneset';
$returnValue = function ($newValue) use (&$value) {
$value = $newValue;
};
$finish = trigger('__call', $this, $method, $params, $returnValue);
$value = $finish($value);
if ($value !== 'noneset') {
return $value;
}
if (static::hasMacro($method)) {
return $this->macroCall($method, $params);
}
throw new BadMethodCallException(sprintf(
'Method %s::%s does not exist.', static::class, $method
));
}
public function tap($callback)
{
$callback($this);
return $this;
}
}

View file

@ -0,0 +1,132 @@
<?php
namespace Livewire;
abstract class ComponentHook
{
protected $component;
function setComponent($component)
{
$this->component = $component;
}
function callBoot(...$params) {
if (method_exists($this, 'boot')) $this->boot(...$params);
}
function callMount(...$params) {
if (method_exists($this, 'mount')) $this->mount(...$params);
}
function callHydrate(...$params) {
if (method_exists($this, 'hydrate')) $this->hydrate(...$params);
}
function callUpdate($propertyName, $fullPath, $newValue) {
$callbacks = [];
if (method_exists($this, 'update')) $callbacks[] = $this->update($propertyName, $fullPath, $newValue);
return function (...$params) use ($callbacks) {
foreach ($callbacks as $callback) {
if (is_callable($callback)) $callback(...$params);
}
};
}
function callCall($method, $params, $returnEarly, $metadata, $componentContext) {
$callbacks = [];
if (method_exists($this, 'call')) $callbacks[] = $this->call($method, $params, $returnEarly, $metadata, $componentContext);
return function (...$params) use ($callbacks) {
foreach ($callbacks as $callback) {
if (is_callable($callback)) $callback(...$params);
}
};
}
function callRender(...$params) {
$callbacks = [];
if (method_exists($this, 'render')) $callbacks[] = $this->render(...$params);
return function (...$params) use ($callbacks) {
foreach ($callbacks as $callback) {
if (is_callable($callback)) $callback(...$params);
}
};
}
function callRenderIsland(...$params) {
$callbacks = [];
if (method_exists($this, 'renderIsland')) $callbacks[] = $this->renderIsland(...$params);
return function (...$params) use ($callbacks) {
foreach ($callbacks as $callback) {
if (is_callable($callback)) $callback(...$params);
}
};
}
function callRenderPlaceholder(...$params) {
$callbacks = [];
if (method_exists($this, 'renderPlaceholder')) $callbacks[] = $this->renderPlaceholder(...$params);
return function (...$params) use ($callbacks) {
foreach ($callbacks as $callback) {
if (is_callable($callback)) $callback(...$params);
}
};
}
function callDehydrate(...$params) {
if (method_exists($this, 'dehydrate')) $this->dehydrate(...$params);
}
function callDestroy(...$params) {
if (method_exists($this, 'destroy')) $this->destroy(...$params);
}
function callException(...$params) {
if (method_exists($this, 'exception')) $this->exception(...$params);
}
function getProperties()
{
return $this->component->all();
}
function getProperty($name)
{
return data_get($this->getProperties(), $name);
}
function storeSet($key, $value)
{
store($this->component)->set($key, $value);
}
function storePush($key, $value, $iKey = null)
{
store($this->component)->push($key, $value, $iKey);
}
function storeGet($key, $default = null)
{
return store($this->component)->get($key, $default);
}
function storeFind($key, $iKey = null, $default = null)
{
return store($this->component)->find($key, $iKey, $default);
}
function storeHas($key)
{
return store($this->component)->has($key);
}
}

View file

@ -0,0 +1,134 @@
<?php
namespace Livewire;
use WeakMap;
use Livewire\Drawer\Utils;
class ComponentHookRegistry
{
protected static $components;
protected static $componentHooks = [];
static function register($hook)
{
if (method_exists($hook, 'provide')) $hook::provide();
if (in_array($hook, static::$componentHooks)) return;
static::$componentHooks[] = $hook;
}
static function getHook($component, $hook)
{
if (! isset(static::$components[$component])) return;
$componentHooks = static::$components[$component];
foreach ($componentHooks as $componentHook) {
if ($componentHook instanceof $hook) return $componentHook;
}
}
static function boot()
{
static::$components = new WeakMap;
foreach (static::$componentHooks as $hook) {
on('mount', function ($component, $params, $key, $parent, $attributes) use ($hook) {
if (! $hook = static::initializeHook($hook, $component)) {
return;
}
$hook->callBoot();
$hook->callMount($params, $parent, $attributes);
});
on('hydrate', function ($component, $memo) use ($hook) {
if (! $hook = static::initializeHook($hook, $component)) {
return;
}
$hook->callBoot();
$hook->callHydrate($memo);
});
}
on('update', function ($component, $fullPath, $newValue) {
$propertyName = Utils::beforeFirstDot($fullPath);
return static::proxyCallToHooks($component, 'callUpdate')($propertyName, $fullPath, $newValue);
});
on('call', function ($component, $method, $params, $componentContext, $earlyReturn, $metadata) {
return static::proxyCallToHooks($component, 'callCall')($method, $params, $earlyReturn, $metadata, $componentContext);
});
on('render', function ($component, $view, $data) {
return static::proxyCallToHooks($component, 'callRender')($view, $data);
});
on('renderIsland', function ($component, $name, $view, $data) {
return static::proxyCallToHooks($component, 'callRenderIsland')($name, $view, $data);
});
on('render.placeholder', function ($component, $view, $data) {
return static::proxyCallToHooks($component, 'callRenderPlaceholder')($view, $data);
});
on('dehydrate', function ($component, $context) {
static::proxyCallToHooks($component, 'callDehydrate')($context);
});
on('destroy', function ($component, $context) {
static::proxyCallToHooks($component, 'callDestroy')($context);
});
on('exception', function ($target, $e, $stopPropagation) {
if ($target instanceof \Livewire\Features\SupportFormObjects\Form) {
$target = $target->getComponent();
}
if ($target instanceof \Livewire\Component) {
static::proxyCallToHooks($target, 'callException')($e, $stopPropagation);
}
});
}
static public function initializeHook($hook, $target)
{
if (! isset(static::$components[$target])) static::$components[$target] = [];
$hook = new $hook;
$hook->setComponent($target);
// If no `skip` method has been implemented, then boot the hook anyway
if (method_exists($hook, 'skip') && $hook->skip()) {
return;
}
static::$components[$target][] = $hook;
return $hook;
}
static function proxyCallToHooks($target, $method) {
return function (...$params) use ($target, $method) {
$forwardCallbacks = [];
foreach (static::$components[$target] ?? [] as $hook) {
if ($callback = $hook->{$method}(...$params)) {
$forwardCallbacks[] = $callback;
}
}
return function (...$forwards) use ($forwardCallbacks) {
foreach ($forwardCallbacks as $callback) {
$callback(...$forwards);
}
};
};
}
}

View file

@ -0,0 +1,160 @@
<?php
namespace Livewire\Concerns;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Livewire\Drawer\Utils;
use Livewire\Form;
trait InteractsWithProperties
{
public function hasProperty($prop)
{
return property_exists($this, Utils::beforeFirstDot($prop));
}
public function getPropertyValue($name)
{
$value = $this->{Utils::beforeFirstDot($name)};
if (Utils::containsDots($name)) {
return data_get($value, Utils::afterFirstDot($name));
}
return $value;
}
public function fill($values)
{
$publicProperties = array_keys($this->all());
$model = $values instanceof Model ? $values : null;
if ($model) $values = $model->toArray();
foreach ($values as $key => $value) {
if (! in_array(Utils::beforeFirstDot($key), $publicProperties)) continue;
try {
data_set($this, $key, $value);
} catch (\TypeError $exception) {
if (! $model) throw $exception;
data_set($this, $key, $model->getAttribute($key));
}
}
}
public function reset(...$properties)
{
$properties = count($properties) && is_array($properties[0])
? $properties[0]
: $properties;
// Reset all
if (empty($properties)) {
$properties = array_keys($this->all());
}
$freshInstance = new static;
foreach ($properties as $property) {
$property = str($property);
// Check if the property contains a dot which means it is actually on a nested object like a FormObject
if (str($property)->contains('.')) {
$propertyName = $property->afterLast('.');
$objectName = $property->before('.');
// form object reset
if (is_subclass_of($this->{$objectName}, Form::class)) {
$this->{$objectName}->reset($propertyName);
continue;
}
$object = data_get($freshInstance, $objectName, null);
if (is_object($object)) {
$isInitialized = (new \ReflectionProperty($object, (string) $propertyName))->isInitialized($object);
} elseif (is_array($object)) {
$isInitialized = Arr::has($freshInstance->{$objectName}, Utils::afterFirstDot((string) $property));
} else {
$isInitialized = false;
}
} else {
// Form objects are typed and have no default, so they appear
// uninitialized on a fresh instance. Reset their internal state
// instead of unsetting the property.
if (isset($this->{$property}) && is_subclass_of($this->{$property}, Form::class)) {
$this->{$property}->reset();
continue;
}
$isInitialized = (new \ReflectionProperty($freshInstance, (string) $property))->isInitialized($freshInstance);
}
// Handle resetting properties that are not initialized by default.
if (! $isInitialized) {
data_forget($this, (string) $property);
continue;
}
data_set($this, $property, data_get($freshInstance, $property));
}
}
public function resetExcept(...$properties)
{
if (count($properties) && is_array($properties[0])) {
$properties = $properties[0];
}
$keysToReset = array_diff(array_keys($this->all()), $properties);
if($keysToReset === []) {
return;
}
$this->reset($keysToReset);
}
public function pull($properties = null)
{
$wantsASingleValue = is_string($properties);
$properties = is_array($properties) ? $properties : func_get_args();
$beforeReset = match (true) {
empty($properties) => $this->all(),
$wantsASingleValue => $this->getPropertyValue($properties[0]),
default => $this->only($properties),
};
$this->reset($properties);
return $beforeReset;
}
public function only($properties)
{
$results = [];
foreach (is_array($properties) ? $properties : func_get_args() as $property) {
$results[$property] = $this->hasProperty($property) ? $this->getPropertyValue($property) : null;
}
return $results;
}
public function except($properties)
{
$properties = is_array($properties) ? $properties : func_get_args();
return array_diff_key($this->all(), array_flip($properties));
}
public function all()
{
return Utils::getPublicPropertiesDefinedOnSubclass($this);
}
}

View file

@ -0,0 +1,206 @@
<?php
namespace Livewire\Drawer;
class BaseUtils
{
protected static $reflectionCache = [];
public static function flushReflectionCache()
{
static::$reflectionCache = [];
}
static function isSyntheticTuple($payload) {
return is_array($payload)
&& count($payload) === 2
&& isset($payload[1]['s']);
}
static function isAPrimitive($target) {
return
is_numeric($target) ||
is_string($target) ||
is_bool($target) ||
is_null($target);
}
static function getPublicPropertiesDefinedOnSubclass($target) {
$class = get_class($target);
if (!isset(static::$reflectionCache[$class])) {
static::$reflectionCache[$class] = static::reflectAndCachePropertyMetadata($target, function ($property) {
return $property->getDeclaringClass()->getName() !== \Livewire\Component::class
&& $property->getDeclaringClass()->getName() !== \Livewire\Volt\Component::class;
});
}
return static::extractPropertyValuesFromInstance($target, static::$reflectionCache[$class]);
}
protected static function reflectAndCachePropertyMetadata($target, $filter = null)
{
return collect((new \ReflectionObject($target))->getProperties())
->filter(function ($property) {
return $property->isPublic() && ! $property->isStatic() && $property->isDefault();
})
->filter($filter ?? fn () => true)
->mapWithKeys(function ($property) {
$type = null;
if (method_exists($property, 'getType') && $property->getType()) {
$type = method_exists($property->getType(), 'getName')
? $property->getType()->getName()
: null;
}
return [$property->getName() => [
'name' => $property->getName(),
'type' => $type,
]];
})
->all();
}
protected static function extractPropertyValuesFromInstance($target, $cachedMetadata)
{
$properties = [];
$reflection = new \ReflectionObject($target); // One reflection object for all properties
foreach ($cachedMetadata as $propertyName => $meta) {
$property = $reflection->getProperty($propertyName);
if (method_exists($property, 'isInitialized') && !$property->isInitialized($target)) {
$value = ($meta['type'] === 'array') ? [] : null;
} else {
$value = $property->getValue($target);
}
$properties[$propertyName] = $value;
}
return $properties;
}
static function getPublicProperties($target, $filter = null)
{
return collect((new \ReflectionObject($target))->getProperties())
->filter(function ($property) {
return $property->isPublic() && ! $property->isStatic() && $property->isDefault();
})
->filter($filter ?? fn () => true)
->mapWithKeys(function ($property) use ($target) {
// Ensures typed property is initialized in PHP >=7.4, if so, return its value,
// if not initialized, return null (as expected in earlier PHP Versions)
if (method_exists($property, 'isInitialized') && !$property->isInitialized($target)) {
// If a type of `array` is given with no value, let's assume users want
// it prefilled with an empty array...
$value = (method_exists($property, 'getType') && $property->getType() && method_exists($property->getType(), 'getName') && $property->getType()->getName() === 'array')
? [] : null;
} else {
$value = $property->getValue($target);
}
return [$property->getName() => $value];
})
->all();
}
static function getPublicMethodsDefinedBySubClass($target)
{
$methods = array_filter((new \ReflectionObject($target))->getMethods(), function ($method) {
$isInBaseComponentClass = $method->getDeclaringClass()->getName() === \Livewire\Component::class || $method->getDeclaringClass()->getName() === \Livewire\Volt\Component::class;
return $method->isPublic()
&& ! $method->isStatic()
&& ! $isInBaseComponentClass;
});
return array_map(function ($method) {
return $method->getName();
}, $methods);
}
static function hasAttribute($target, $property, $attributeClass) {
$property = static::getProperty($target, $property);
foreach ($property->getAttributes() as $attribute) {
$instance = $attribute->newInstance();
if ($instance instanceof $attributeClass) return true;
}
return false;
}
static function getProperty($target, $property) {
return (new \ReflectionObject($target))->getProperty($property);
}
static function propertyIsTyped($target, $property) {
$property = static::getProperty($target, $property);
return $property->hasType();
}
static function propertyIsTypedAndUninitialized($target, $property) {
$property = static::getProperty($target, $property);
return $property->hasType() && (! $property->isInitialized($target));
}
/**
* Compare a value's native PHP type with a property's declared type.
*
* This deliberately does not apply PHP's weak scalar coercion. It returns
* null when the property is missing or untyped because there is no declared
* type contract to compare the value against.
*/
static function propertyTypeMatchesValue($target, $property, $value): ?bool {
if (! $property || ! property_exists($target, $property)) return null;
$reflectionProperty = static::getProperty($target, $property);
if (! $type = $reflectionProperty->getType()) return null;
return static::typeMatchesValue($type, $value, $reflectionProperty->getDeclaringClass());
}
protected static function typeMatchesValue($type, $value, $declaringClass): bool {
if ($value === null) return $type->allowsNull();
if ($type instanceof \ReflectionUnionType) {
foreach ($type->getTypes() as $unionType) {
if (static::typeMatchesValue($unionType, $value, $declaringClass)) return true;
}
return false;
}
if ($type instanceof \ReflectionIntersectionType) {
foreach ($type->getTypes() as $intersectionType) {
if (! static::typeMatchesValue($intersectionType, $value, $declaringClass)) return false;
}
return true;
}
$name = $type->getName();
return match ($name) {
'mixed' => true,
'string' => is_string($value),
'int' => is_int($value),
'float' => is_float($value),
'bool' => is_bool($value),
'array' => is_array($value),
'object' => is_object($value),
'iterable' => is_iterable($value),
'callable' => is_callable($value),
'false' => $value === false,
'true' => $value === true,
'self', 'static' => $value instanceof ($declaringClass->getName()),
'parent' => ($parent = $declaringClass->getParentClass()) && $value instanceof ($parent->getName()),
default => $value instanceof $name,
};
}
}

View file

@ -0,0 +1,192 @@
<?php
namespace Livewire\Drawer;
use Illuminate\Routing\Exceptions\BackedEnumCaseNotFoundException;
use BackedEnum;
use ReflectionClass;
use ReflectionMethod;
use Livewire\Component;
use Illuminate\Support\Reflector;
use Illuminate\Support\Collection;
use Illuminate\Routing\Route;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Contracts\Routing\UrlRoutable;
/**
* This class mirrors the functionality of Laravel's Illuminate\Routing\ImplicitRouteBinding class.
*/
class ImplicitRouteBinding
{
protected $container;
public function __construct($container)
{
$this->container = $container;
}
public function resolveAllParameters(Route $route, Component $component)
{
// Resolve every bindable route parameter in URI order first (like Laravel's
// own implicit binding) so that scoped child bindings always see their
// parent as an already-resolved model, regardless of whether the parent
// is a public property or a mount() parameter...
$this->resolveRouteParametersInOrder($route, $component);
$params = $this->resolveMountParameters($route, $component);
$props = $this->resolveComponentProps($route, $component);
return $params->merge($props)->all();
}
protected function resolveRouteParametersInOrder(Route $route, Component $component)
{
$types = $this->getPublicPropertyTypes($component)
->merge($this->getMountParameterTypes($component)->filter())
->filter(function ($className) {
return $className && (is_subclass_of($className, UrlRoutable::class) || is_subclass_of($className, BackedEnum::class));
});
foreach ($route->parametersWithoutNulls() as $name => $value) {
if (! $types->has($name)) continue;
$route->setParameter($name, $this->resolveParameter($route, $name, $types->get($name)));
}
}
protected function getMountParameterTypes(Component $component)
{
if (! method_exists($component, 'mount')) {
return new Collection();
}
return collect((new ReflectionMethod($component, 'mount'))->getParameters())
->mapWithKeys(function ($parameter) {
return [$parameter->getName() => Reflector::getParameterClassName($parameter)];
});
}
public function resolveMountParameters(Route $route, Component $component)
{
if (! method_exists($component, 'mount')) {
return new Collection();
}
// Cache the current route action (this callback actually), just to be safe.
$cache = $route->getAction();
// We'll set the route action to be the "mount" method from the chosen
// Livewire component, to get the proper implicit bindings.
$route->uses(get_class($component).'@mount');
try {
// This is normally handled in the "SubstituteBindings" middleware, but
// because that middleware has already ran, we need to run them again.
$this->container['router']->substituteImplicitBindings($route);
$mountMethod = new ReflectionMethod($component, 'mount');
// Only pass route parameters that match the mount method's signature.
// Without this, unmatched route parameters would be classified as
// HTML attributes and bleed into child Blade component constructors.
$mountParamNames = array_map(fn ($p) => $p->getName(), $mountMethod->getParameters());
$routeParams = array_intersect_key($route->parameters(), array_flip($mountParamNames));
$parameters = $route->resolveMethodDependencies($routeParams, $mountMethod);
// Restore the original route action...
$route->setAction($cache);
} catch(\Exception $e) {
// Restore the original route action before an exception is thrown...
$route->setAction($cache);
throw $e;
}
return new Collection($parameters);
}
public function resolveComponentProps(Route $route, Component $component)
{
return $this->getPublicPropertyTypes($component)
->intersectByKeys($route->parametersWithoutNulls())
->sortBy(function ($className, $propName) use ($route) {
return array_search($propName, array_keys($route->parametersWithoutNulls()));
})
->map(function ($className, $propName) use ($route) {
// If typed public property, resolve the class
if ($className) {
$resolved = $this->resolveParameter($route, $propName, $className);
// We'll also pass the resolved model back to the route
// so that it can be used for any depending on bindings
$route->setParameter($propName, $resolved);
return $resolved;
}
// Otherwise, just return the route parameter
return $route->parameter($propName);
});
}
public function getPublicPropertyTypes($component)
{
return collect(Utils::getPublicPropertiesDefinedOnSubclass($component))
->map(function ($value, $name) use ($component) {
return Reflector::getParameterClassName(new \ReflectionProperty($component, $name));
});
}
protected function resolveParameter($route, $parameterName, $parameterClassName)
{
$parameterValue = $route->parameter($parameterName);
if ($parameterValue instanceof UrlRoutable) {
return $parameterValue;
}
if($enumValue = $this->resolveEnumParameter($parameterValue, $parameterClassName)) {
return $enumValue;
}
$instance = $this->container->make($parameterClassName);
$parent = $route->parentOfParameter($parameterName);
if ($parent instanceof UrlRoutable && ! $route->preventsScopedBindings() && ($route->enforcesScopedBindings() || array_key_exists($parameterName, $route->bindingFields()))) {
$model = $parent->resolveChildRouteBinding($parameterName, $parameterValue, $route->bindingFieldFor($parameterName));
} else {
if ($route->allowsTrashedBindings()) {
$model = $instance->resolveSoftDeletableRouteBinding($parameterValue, $route->bindingFieldFor($parameterName));
} else {
$model = $instance->resolveRouteBinding($parameterValue, $route->bindingFieldFor($parameterName));
}
}
if (! $model) {
throw (new ModelNotFoundException())->setModel(get_class($instance), [$parameterValue]);
}
return $model;
}
protected function resolveEnumParameter($parameterValue, $parameterClassName)
{
if ($parameterValue instanceof BackedEnum) {
return $parameterValue;
}
if ((new ReflectionClass($parameterClassName))->isEnum()) {
$enumValue = $parameterClassName::tryFrom($parameterValue);
if (is_null($enumValue)) {
throw new BackedEnumCaseNotFoundException($parameterClassName, $parameterValue);
}
return $enumValue;
}
return null;
}
}

View file

@ -0,0 +1,197 @@
<?php
namespace Livewire\Drawer;
class Regexes
{
static $livewireOpeningTag = "
<
\s*
livewire[-\:]([\w\-\:\.]*)
(?<attributes>
(?:
\s+
(?:
(?:
@(?:class)(\( (?: (?>[^()]+) | (?-1) )* \))
)
|
(?:
@(?:style)(\( (?: (?>[^()]+) | (?-1) )* \))
)
|
(?:
\{\{\s*\\\$attributes(?:[^}]+?)?\s*\}\}
)
|
(?:
(\:\\\$)(\w+)
)
|
(?:
[\w\-:.@%]+
(
=
(?:
\\\"[^\\\"]*\\\"
|
\'[^\']*\'
|
[^\'\\\"=<>]+
)
)?
)
)
)*
\s*
)
(?<![\/=\-])
>
";
static $livewireOpeningTagOrSelfClosingTag = "
<
\s*
livewire[-\:]([\w\-\:\.]*)
(?<attributes>
(?:
\s+
(?:
(?:
@(?:class)(\( (?: (?>[^()]+) | (?-1) )* \))
)
|
(?:
@(?:style)(\( (?: (?>[^()]+) | (?-1) )* \))
)
|
(?:
\{\{\s*\\\$attributes(?:[^}]+?)?\s*\}\}
)
|
(?:
(\:\\\$)(\w+)
)
|
(?:
[\w\-:.@%]+
(
=
(?:
\\\"[^\\\"]*\\\"
|
\'[^\']*\'
|
[^\'\\\"=<>]+
)
)?
)
)
)*
\s*
)
\/?>
";
static $livewireSelfClosingTag = "
<
\s*
livewire[-\:]([\w\-\:\.]*)
\s*
(?<attributes>
(?:
\s+
(?:
(?:
@(?:class)(\( (?: (?>[^()]+) | (?-1) )* \))
)
|
(?:
@(?:style)(\( (?: (?>[^()]+) | (?-1) )* \))
)
|
(?:
\{\{\s*\\\$attributes(?:[^}]+?)?\s*\}\}
)
|
(?:
(\:\\\$)(\w+)
)
|
(?:
[\w\-:.@%]+
(
=
(?:
\\\"[^\\\"]*\\\"
|
\'[^\']*\'
|
[^\'\\\"=<>]+
)
)?
)
)
)*
\s*
)
\/>
";
static $livewireClosingTag = '<\/\s*livewire[-\:][\w\-\:\.]*\s*>';
static $slotOpeningTag = "
<
\s*
livewire[\-\:]slot
(?:\:(?<inlineName>\w+(?:-\w+)*))?
(?:\s+(:?)name=(?<name>(\"[^\"]+\"|\\\'[^\\\']+\\\'|[^\s>]+)))?
(?<attributes>
(?:
\s+
(?:
(?:
@(?:class)(\( (?: (?>[^()]+) | (?-1) )* \))
)
|
(?:
@(?:style)(\( (?: (?>[^()]+) | (?-1) )* \))
)
|
(?:
\{\{\s*\\\$attributes(?:[^}]+?)?\s*\}\}
)
|
(?:
(\:\\\$)(\w+)
)
|
(?:
[\w\-:.@%]+
(
=
(?:
\\\"[^\\\"]*\\\"
|
\'[^\']*\'
|
[^\'\\\"=<>]+
)
)?
)
)
)*
\s*
)
(?<![\/=\-])
>
";
static $slotClosingTag = '<\/\s*livewire[\-\:]slot[^>]*>';
static $bladeDirective = "\B@(@?\w+(?:::\w+)?)([ \t]*)(\( ( (?>[^()]+) | (?3) )* \))?";
static function specificBladeDirective($directive) {
return "(@?$directive(?:::\w+)?)([ \t]*)(\( ( (?>[^()]+) | (?3) )* \))";
}
}

View file

@ -0,0 +1,208 @@
<?php
namespace Livewire\Drawer;
use Illuminate\Http\Request;
use Livewire\Exceptions\RootTagMissingFromViewException;
use Livewire\Features\SupportFileUploads\FileUploadConfiguration;
use function Livewire\invade;
class Utils extends BaseUtils
{
static function insertAttributesIntoHtmlRoot($html, $attributes) {
$attributesFormattedForHtmlElement = static::stringifyHtmlAttributes($attributes);
preg_match('/(?:\n\s*|^\s*)<([a-zA-Z0-9\-]+)/', $html, $matches, PREG_OFFSET_CAPTURE);
throw_unless(
count($matches),
new RootTagMissingFromViewException
);
$tagName = $matches[1][0];
$lengthOfTagName = strlen($tagName);
$positionOfFirstCharacterInTagName = $matches[1][1];
return substr_replace(
$html,
' '.$attributesFormattedForHtmlElement,
$positionOfFirstCharacterInTagName + $lengthOfTagName,
0
);
}
static function stringifyHtmlAttributes($attributes)
{
return collect($attributes)
->mapWithKeys(function ($value, $key) {
return [$key => static::escapeStringForHtml($value)];
})->map(function ($value, $key) {
return sprintf('%s="%s"', $key, $value);
})->implode(' ');
}
static function escapeStringForHtml($subject)
{
if (is_string($subject) || is_numeric($subject)) {
return htmlspecialchars($subject, ENT_QUOTES|ENT_SUBSTITUTE);
}
return htmlspecialchars(json_encode($subject, JSON_THROW_ON_ERROR), ENT_QUOTES|ENT_SUBSTITUTE);
}
static function pretendResponseIsFile($file, $contentType = 'application/javascript; charset=utf-8')
{
$lastModified = filemtime($file);
return static::cachedFileResponse($file, $contentType, $lastModified,
fn ($headers) => response()->file($file, $headers));
}
static function pretendResponseIsFileFromString($content, $filemtime, $filename = 'generated', $contentType = 'application/javascript; charset=utf-8')
{
return static::cachedFileResponse($filename, $contentType, $filemtime,
fn ($headers) => response($content, 200, $headers));
}
static function pretendPreviewResponseIsPreviewFile($filename)
{
$file = FileUploadConfiguration::path($filename);
$storage = FileUploadConfiguration::storage();
$mimeType = FileUploadConfiguration::mimeType($filename);
$lastModified = FileUploadConfiguration::lastModified($file);
return self::cachedFileResponse($filename, $mimeType, $lastModified,
fn ($headers) => $storage->download($file, $filename, $headers));
}
static private function cachedFileResponse($filename, $contentType, $lastModified, $downloadCallback)
{
$expires = strtotime('+1 year');
$cacheControl = 'public, max-age=31536000';
if (static::matchesCache($lastModified)) {
return response('', 304, [
'Expires' => static::httpDate($expires),
'Cache-Control' => $cacheControl,
]);
}
$headers = [
'Content-Type' => $contentType,
'Expires' => static::httpDate($expires),
'Cache-Control' => $cacheControl,
'Last-Modified' => static::httpDate($lastModified),
];
if (str($filename)->endsWith('.br')) {
$headers['Content-Encoding'] = 'br';
}
return $downloadCallback($headers);
}
static function matchesCache($lastModified)
{
$ifModifiedSince = app(Request::class)->header('if-modified-since');
return $ifModifiedSince !== null && @strtotime($ifModifiedSince) === $lastModified;
}
static function httpDate($timestamp)
{
return sprintf('%s GMT', gmdate('D, d M Y H:i:s', $timestamp));
}
static function containsDots($subject)
{
return str_contains($subject, '.');
}
static function dotSegments($subject)
{
return explode('.', $subject);
}
static function beforeFirstDot($subject)
{
return head(explode('.', $subject));
}
static function afterFirstDot($subject) : string
{
return str($subject)->after('.');
}
static public function hasProperty($target, $property)
{
return property_exists($target, static::beforeFirstDot($property));
}
static public function shareWithViews($name, $value)
{
$old = app('view')->shared($name, 'notfound');
app('view')->share($name, $value);
return $revert = function () use ($name, $old) {
if ($old === 'notfound') {
unset(invade(app('view'))->shared[$name]);
} else {
app('view')->share($name, $old);
}
};
}
static function generateBladeView($subject, $data = [])
{
if (! is_string($subject)) {
return tap($subject)->with($data);
}
$component = new class($subject) extends \Illuminate\View\Component
{
protected $template;
public function __construct($template)
{
$this->template = $template;
}
public function render()
{
return $this->template;
}
};
$view = app('view')->make($component->resolveView(), $data);
return $view;
}
static function applyMiddleware(\Illuminate\Http\Request $request, $middleware = [])
{
$response = (new \Illuminate\Pipeline\Pipeline(app()))
->send($request)
->through($middleware)
->then(function() {
return new \Illuminate\Http\Response();
});
if ($response instanceof \Illuminate\Http\RedirectResponse) {
abort($response);
}
return $response;
}
static function extractAttributeDataFromHtml($html, $attribute)
{
$data = (string) str($html)->betweenFirst($attribute.'="', '"');
return json_decode(
htmlspecialchars_decode($data, ENT_QUOTES|ENT_SUBSTITUTE),
associative: true,
);
}
}

View file

@ -0,0 +1,108 @@
<?php
declare(strict_types=1);
namespace Livewire;
class EventBus
{
protected array $listeners = [];
protected array $listenersAfter = [];
protected array $listenersBefore = [];
public function boot(): void
{
app()->singleton($this::class);
}
public function on(string $name, callable $callback): callable
{
$this->listeners[$name][] = $callback;
return fn() => $this->off($name, $callback);
}
public function before(string $name, callable $callback): callable
{
$this->listenersBefore[$name][] = $callback;
return fn() => $this->off($name, $callback);
}
public function after(string $name, callable $callback): callable
{
$this->listenersAfter[$name][] = $callback;
return fn() => $this->off($name, $callback);
}
public function off(string $name, callable $callback): void
{
if (isset($this->listeners[$name])) {
$index = array_search($callback, $this->listeners[$name], true);
if ($index !== false) {
unset($this->listeners[$name][$index]);
return;
}
}
if (isset($this->listenersAfter[$name])) {
$index = array_search($callback, $this->listenersAfter[$name], true);
if ($index !== false) {
unset($this->listenersAfter[$name][$index]);
return;
}
}
if (isset($this->listenersBefore[$name])) {
$index = array_search($callback, $this->listenersBefore[$name], true);
if ($index !== false) {
unset($this->listenersBefore[$name][$index]);
}
}
}
public function trigger(string $name, ...$params): callable
{
$middlewares = [];
$listeners = [];
if (isset($this->listenersBefore[$name])) {
$listeners = $this->listenersBefore[$name];
}
if (isset($this->listeners[$name])) {
$listeners = array_merge($listeners, $this->listeners[$name]);
}
if (isset($this->listenersAfter[$name])) {
$listeners = array_merge($listeners, $this->listenersAfter[$name]);
}
foreach ($listeners as $callback) {
$result = $callback(...$params);
if ($result !== null) {
$middlewares[] = $result;
}
}
return function (&$forward = null, ...$extras) use ($middlewares) {
foreach ($middlewares as $finisher) {
if ($finisher === null) continue;
$finisher = is_array($finisher) ? end($finisher) : $finisher;
$result = $finisher($forward, ...$extras);
$forward = $result ?? $forward;
}
return $forward;
};
}
}

View file

@ -0,0 +1,8 @@
<?php
namespace Livewire\Exceptions;
trait BypassViewHandler
{
//
}

View file

@ -0,0 +1,13 @@
<?php
namespace Livewire\Exceptions;
class ComponentAttributeMissingOnDynamicComponentException extends \Exception
{
use BypassViewHandler;
public function __construct()
{
parent::__construct('Dynamic component tag is missing component attribute.');
}
}

View file

@ -0,0 +1,8 @@
<?php
namespace Livewire\Exceptions;
class ComponentNotFoundException extends \Exception
{
use BypassViewHandler;
}

View file

@ -0,0 +1,11 @@
<?php
namespace Livewire\Exceptions;
class EventHandlerDoesNotExist extends \Exception
{
public function __construct(public readonly string $eventName)
{
parent::__construct('Handler for event ' . $eventName . ' does not exist');
}
}

View file

@ -0,0 +1,17 @@
<?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."
);
}
}

View file

@ -0,0 +1,14 @@
<?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);
}
}

View file

@ -0,0 +1,29 @@
<?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"
);
}
public function report(): bool
{
return ! config('app.debug');
}
// In debug mode, let Laravel render the full error page.
// In production, return a generic 419 to avoid leaking details.
public function render($request)
{
if (config('app.debug')) return false;
return response('', 419);
}
}

View file

@ -0,0 +1,17 @@
<?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}]."
);
}
}

View file

@ -0,0 +1,16 @@
<?php
namespace Livewire\Exceptions;
class ModelableRootHasWireModelException extends \Exception
{
use BypassViewHandler;
public function __construct()
{
parent::__construct(
"A #[Modelable] component's root element cannot have wire:model. " .
"Wrap your input element in a <div> so Livewire can inject the parent binding on the root element."
);
}
}

View file

@ -0,0 +1,13 @@
<?php
namespace Livewire\Exceptions;
class NonPublicComponentMethodCall extends \Exception
{
use BypassViewHandler;
public function __construct($method)
{
parent::__construct('Component method not found: ['.$method.']');
}
}

View file

@ -0,0 +1,18 @@
<?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);
}
}

View file

@ -0,0 +1,15 @@
<?php
namespace Livewire\Exceptions;
class PropertyNotFoundException extends \Exception
{
use BypassViewHandler;
public function __construct($property, $component)
{
parent::__construct(
"Property [\${$property}] not found on component: [{$component}]"
);
}
}

View file

@ -0,0 +1,15 @@
<?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}]"
);
}
}

View file

@ -0,0 +1,16 @@
<?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."
);
}
}

View file

@ -0,0 +1,15 @@
<?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);
}
}

View file

@ -0,0 +1,15 @@
<?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);
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace Livewire\Facades;
use Illuminate\Support\Facades\Facade;
/**
* @internal
*
* @method static string forLocal()
* @method static string forS3($file, $visibility = 'private')
* @method static string signedRoute($name, $expiration, $parameters = [])
*
* @see \Livewire\Features\SupportFileUploads\GenerateSignedUploadUrl
*/
class GenerateSignedUploadUrlFacade extends Facade
{
public static function getFacadeAccessor()
{
return \Livewire\Features\SupportFileUploads\GenerateSignedUploadUrl::class;
}
}

View file

@ -0,0 +1,110 @@
<?php
namespace Livewire\Factory;
use Livewire\Exceptions\ComponentNotFoundException;
use Livewire\Compiler\Compiler;
use Livewire\Finder\Finder;
use Livewire\Component;
class Factory
{
protected $missingComponentResolvers = [];
protected $resolvedComponentCache = [];
public function __construct(
protected Finder $finder,
protected Compiler $compiler,
) {}
public function create($name, $id = null): Component
{
[$name, $class] = $this->resolveComponentNameAndClass($name);
$component = new $class;
$component->setId($id ?: str()->random(20));
$component->setName($name);
return $component;
}
public function resolveMissingComponent($resolver): void
{
$this->missingComponentResolvers[] = $resolver;
}
public function resolveComponentNameAndClass($name): array
{
$name = $this->finder->normalizeName($name);
$class = null;
if (isset($this->resolvedComponentCache[$name])) {
return [$name, $this->resolvedComponentCache[$name]];
}
if ($name) {
$class = $this->finder->resolveClassComponentClassName($name);
if (! $class) {
$path = $this->finder->resolveMultiFileComponentPath($name);
if (! $path) {
$path = $this->finder->resolveSingleFileComponentPath($name);
}
if ($path) {
$class = $this->compiler->compile($path);
}
}
}
if (! $class || ! class_exists($class) || ! is_subclass_of($class, Component::class)) {
foreach ($this->missingComponentResolvers as $resolver) {
if ($class = $resolver($name)) {
$this->finder->addComponent(name: $name, class: $class);
break;
}
}
}
if (! $class || ! class_exists($class) || ! is_subclass_of($class, Component::class)) {
throw new ComponentNotFoundException(
"Unable to find component: [{$name}]"
);
}
$this->resolvedComponentCache[$name] = $class;
return [$name, $class];
}
public function resolveComponentClass($name): string
{
[$name, $class] = $this->resolveComponentNameAndClass($name);
return $class;
}
public function resolveComponentName($name): string
{
$component = $this->create($name);
return $component->getName();
}
public function exists($name): bool
{
try {
$this->create($name);
return true;
} catch (ComponentNotFoundException $e) {
return false;
}
}
}

View file

@ -0,0 +1,16 @@
<?php
namespace Livewire\Features\SupportAsync;
use Livewire\Features\SupportAttributes\Attribute as LivewireAttribute;
#[\Attribute]
class BaseAsync extends LivewireAttribute
{
public function dehydrate($context)
{
$methodName = $this->getName();
$context->pushMemo('async', $methodName);
}
}

View file

@ -0,0 +1,134 @@
<?php
namespace Livewire\Features\SupportAttributes;
use Livewire\Component;
use function Livewire\store;
abstract class Attribute
{
protected Component $component;
protected $subTarget;
protected $subName;
protected AttributeLevel $level;
protected $levelName;
function __boot($component, AttributeLevel $level, $name = null, $subName = null, $subTarget = null)
{
$this->component = $component;
$this->subName = $subName;
$this->subTarget = $subTarget;
$this->level = $level;
$this->levelName = $name;
}
function getComponent()
{
return $this->component;
}
function getSubTarget()
{
return $this->subTarget;
}
function getSubName()
{
return $this->subName;
}
function getLevel()
{
return $this->level;
}
function getName()
{
return $this->levelName;
}
function getValue()
{
if ($this->level !== AttributeLevel::PROPERTY) {
throw new \Exception('Can\'t get the value of a non-property attribute.');
}
return data_get($this->component->all(), $this->levelName);
}
function setValue($value, ?bool $nullable = false)
{
if ($this->level !== AttributeLevel::PROPERTY) {
throw new \Exception('Can\'t set the value of a non-property attribute.');
}
if ($enum = $this->tryingToSetStringOrIntegerToEnum($value)) {
if($nullable) {
$value = $enum::tryFrom($value);
}
else {
$value = $enum::from($value);
}
}
data_set($this->component, $this->levelName, $value);
}
protected function tryingToSetStringOrIntegerToEnum($subject)
{
if (! is_string($subject) && ! is_int($subject)) return;
$target = $this->subTarget ?? $this->component;
$name = $this->subName ?? $this->levelName;
$property = str($name)->before('.')->toString();
$reflection = new \ReflectionProperty($target, $property);
$type = $reflection->getType();
// If the type is available, display its name
if ($type instanceof \ReflectionNamedType) {
$name = $type->getName();
// If the type is a BackedEnum then return it's name
if (is_subclass_of($name, \BackedEnum::class)) {
return $name;
}
}
return false;
}
function storeSet($key, $value)
{
store($this->component)->set($key, $value);
}
function storePush($key, $value, $iKey = null)
{
store($this->component)->push($key, $value, $iKey);
}
function storeGet($key, $default = null)
{
return store($this->component)->get($key, $default);
}
function storeFind($key, $iKey = null, $default = null)
{
return store($this->component)->find($key, $iKey, $default);
}
function storeHas($key)
{
return store($this->component)->has($key);
}
}

View file

@ -0,0 +1,55 @@
<?php
namespace Livewire\Features\SupportAttributes;
use Illuminate\Support\Collection;
use ReflectionAttribute;
use ReflectionObject;
class AttributeCollection extends Collection
{
static function fromComponent($component, $subTarget = null, $propertyNamePrefix = '')
{
$instance = new static;
$reflected = new ReflectionObject($subTarget ?? $component);
foreach (static::getClassAttributesRecursively($reflected) as $attribute) {
$instance->push(tap($attribute->newInstance(), function ($attribute) use ($component, $subTarget) {
$attribute->__boot($component, AttributeLevel::ROOT, null, null, $subTarget);
}));
}
foreach ($reflected->getMethods() as $method) {
foreach ($method->getAttributes(Attribute::class, ReflectionAttribute::IS_INSTANCEOF) as $attribute) {
$instance->push(tap($attribute->newInstance(), function ($attribute) use ($component, $method, $propertyNamePrefix, $subTarget) {
$attribute->__boot($component, AttributeLevel::METHOD, $propertyNamePrefix . $method->getName(), $method->getName(), $subTarget);
}));
}
}
foreach ($reflected->getProperties() as $property) {
foreach ($property->getAttributes(Attribute::class, ReflectionAttribute::IS_INSTANCEOF) as $attribute) {
$instance->push(tap($attribute->newInstance(), function ($attribute) use ($component, $property, $propertyNamePrefix, $subTarget) {
$attribute->__boot($component, AttributeLevel::PROPERTY, $propertyNamePrefix . $property->getName(), $property->getName(), $subTarget);
}));
}
}
return $instance;
}
protected static function getClassAttributesRecursively($reflected) {
$attributes = [];
while ($reflected) {
foreach ($reflected->getAttributes(Attribute::class, ReflectionAttribute::IS_INSTANCEOF) as $attribute) {
$attributes[] = $attribute;
}
$reflected = $reflected->getParentClass();
}
return $attributes;
}
}

View file

@ -0,0 +1,10 @@
<?php
namespace Livewire\Features\SupportAttributes;
enum AttributeLevel
{
case ROOT;
case PROPERTY;
case METHOD;
}

View file

@ -0,0 +1,25 @@
<?php
namespace Livewire\Features\SupportAttributes;
trait HandlesAttributes
{
protected AttributeCollection $attributes;
function getAttributes()
{
return $this->attributes ??= AttributeCollection::fromComponent($this);
}
function setPropertyAttribute($property, $attribute)
{
$attribute->__boot($this, AttributeLevel::PROPERTY, $property);
$this->mergeOutsideAttributes(new AttributeCollection([$attribute]));
}
function mergeOutsideAttributes(AttributeCollection $attributes)
{
$this->attributes = $this->getAttributes()->concat($attributes);
}
}

View file

@ -0,0 +1,125 @@
<?php
namespace Livewire\Features\SupportAttributes;
use Livewire\Features\SupportAttributes\Attribute as LivewireAttribute;
use Livewire\ComponentHook;
class SupportAttributes extends ComponentHook
{
function boot(...$params)
{
$this->getLivewireAttributes()->each(function ($attribute) use ($params) {
if (method_exists($attribute, 'boot')) {
$attribute->boot(...$params);
}
});
}
function mount(...$params)
{
$this->getLivewireAttributes()->each(function ($attribute) use ($params) {
if (method_exists($attribute, 'mount')) {
$attribute->mount(...$params);
}
});
}
function hydrate(...$params)
{
$this->getLivewireAttributes()->each(function ($attribute) use ($params) {
if (method_exists($attribute, 'hydrate')) {
$attribute->hydrate(...$params);
}
});
}
function update($propertyName, $fullPath, $newValue)
{
$callbacks = $this->getLivewireAttributes()
->filter(fn ($attr) => $attr->getLevel() === AttributeLevel::PROPERTY)
// Call "update" on the root property attribute even if it's a deep update...
->filter(fn ($attr) => str($fullPath)->startsWith($attr->getName() . '.') || $fullPath === $attr->getName())
->map(function ($attribute) use ($fullPath, $newValue) {
if (method_exists($attribute, 'update')) {
return $attribute->update($fullPath, $newValue);
}
});
return function (...$params) use ($callbacks) {
foreach ($callbacks as $callback) {
if (is_callable($callback)) $callback(...$params);
}
};
}
function call($method, $params, $returnEarly)
{
$callbacks = $this->getLivewireAttributes()
->filter(fn ($attr) => $attr->getLevel() === AttributeLevel::METHOD)
->filter(fn ($attr) => $attr->getName() === $method)
->map(function ($attribute) use ($params, $returnEarly) {
if (method_exists($attribute, 'call')) {
return $attribute->call($params, $returnEarly);
}
});
return function (...$params) use ($callbacks) {
foreach ($callbacks as $callback) {
if (is_callable($callback)) $callback(...$params);
}
};
}
function render(...$params)
{
$callbacks = $this->getLivewireAttributes()
->map(function ($attribute) use ($params) {
if (method_exists($attribute, 'render')) {
return $attribute->render(...$params);
}
});
return function (...$params) use ($callbacks) {
foreach ($callbacks as $callback) {
if (is_callable($callback)) {
$callback(...$params);
}
}
};
}
function dehydrate(...$params)
{
$this->getLivewireAttributes()->each(function ($attribute) use ($params) {
if (method_exists($attribute, 'dehydrate')) {
$attribute->dehydrate(...$params);
}
});
}
function destroy(...$params)
{
$this->getLivewireAttributes()->each(function ($attribute) use ($params) {
if (method_exists($attribute, 'destroy')) {
$attribute->destroy(...$params);
}
});
}
function exception(...$params)
{
$this->getLivewireAttributes()->each(function ($attribute) use ($params) {
if (method_exists($attribute, 'exception')) {
$attribute->exception(...$params);
}
});
}
protected function getLivewireAttributes()
{
return $this->component
->getAttributes()
->whereInstanceOf(LivewireAttribute::class);
}
}

View file

@ -0,0 +1,86 @@
<?php
namespace Livewire\Features\SupportAuthorization;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Arr;
use Livewire\Features\SupportAttributes\Attribute as LivewireAttribute;
use Livewire\ImplicitlyBoundMethod;
use function Illuminate\Support\enum_value;
use function Livewire\wrap;
#[\Attribute(\Attribute::IS_REPEATABLE | \Attribute::TARGET_METHOD)]
class BaseAuthorize extends LivewireAttribute
{
use AuthorizesRequests;
public function __construct(
public \UnitEnum|string $ability,
public array|string|null $argument = null,
) {}
public function call(array $parameters) : void
{
wrap($this->component)->tap(function () use ($parameters) {
// Authorize defined gate or class name
if (is_null($this->argument)) {
$this->authorize($this->ability);
return;
}
// Resolve method dependencies lazily, then reuse them for multi-argument authorization checks...
$methodDependencies = null;
$resolveMethodDependencies = function () use (&$methodDependencies, $parameters): array {
return $methodDependencies ??= ImplicitlyBoundMethod::resolveMethodDependencies(
app(),
[$this->component, $this->getName()],
$parameters,
);
};
// Resolve each argument (prioritize method parameters first, then component properties)
$resolved = [];
foreach (Arr::wrap($this->argument) as $arg) {
$resolved[] = $this->resolveArgument($arg, $resolveMethodDependencies);
}
$this->authorize($this->ability, $resolved);
});
}
protected function resolveArgument(string $arg, \Closure $resolveMethodDependencies): mixed
{
// Action that does not require a model, for example a 'create' action...
if (class_exists($arg)) {
return $arg;
}
// Try method parameter first (prioritized per rules)
$methodArgument = Arr::first(
(new \ReflectionMethod($this->component, $this->getName()))->getParameters(),
fn (\ReflectionParameter $parameter) : bool => $parameter->getName() === $arg,
);
if ($methodArgument instanceof \ReflectionParameter) {
$methodDependencies = $resolveMethodDependencies();
return $methodDependencies['named'][$arg];
}
// Fall back to component property
return data_get($this->component, $arg);
}
protected function parseAbilityAndArguments($ability, $arguments)
{
$ability = enum_value($ability);
if (is_string($ability) && ! str_contains($ability, '\\')) {
return [$ability, $arguments];
}
return [$this->normalizeGuessedAbilityName($this->getName()), $ability];
}
}

View file

@ -0,0 +1,98 @@
<?php
namespace Livewire\Features\SupportAutoInjectedAssets;
use Illuminate\Foundation\Http\Events\RequestHandled;
use Livewire\ComponentHook;
use Livewire\Features\SupportScriptsAndAssets\SupportScriptsAndAssets;
use Livewire\Mechanisms\FrontendAssets\FrontendAssets;
use function Livewire\on;
class SupportAutoInjectedAssets extends ComponentHook
{
static $hasRenderedAComponentThisRequest = false;
static $forceAssetInjection = false;
static function provide()
{
on('flush-state', function () {
static::$hasRenderedAComponentThisRequest = false;
static::$forceAssetInjection = false;
});
app('events')->listen(RequestHandled::class, function ($handled) {
// If this is a successful HTML response...
if (! str($handled->response->headers->get('content-type'))->contains('text/html')) return;
if (! method_exists($handled->response, 'status') || $handled->response->status() !== 200) return;
$assetsHead = '';
$assetsBody = '';
// If `@assets` has been used outside of a Livewire component then we need
// to process those assets to be injected alongside the other assets...
SupportScriptsAndAssets::processNonLivewireAssets();
$assets = array_values(SupportScriptsAndAssets::getAssets());
// If there are additional head assets, inject those...
if (count($assets) > 0) {
foreach ($assets as $asset) {
$assetsHead .= $asset."\n";
}
}
// If we're injecting Livewire assets...
if (static::shouldInjectLivewireAssets()) {
$assetsHead .= FrontendAssets::styles()."\n";
$assetsBody .= FrontendAssets::scripts()."\n";
}
if (trim($assetsHead) === '' && trim($assetsBody) === '') return;
$html = $handled->response->getContent();
if (str($html)->contains('</html>')) {
$originalContent = $handled->response->original;
$handled->response->setContent(static::injectAssets($html, $assetsHead, $assetsBody));
$handled->response->original = $originalContent;
}
});
}
protected static function shouldInjectLivewireAssets()
{
if (! static::$forceAssetInjection && config('livewire.inject_assets', true) === false) return false;
if ((! static::$hasRenderedAComponentThisRequest) && (! static::$forceAssetInjection)) return false;
return true;
}
protected static function getLivewireAssets()
{
$livewireStyles = FrontendAssets::styles();
$livewireScripts = FrontendAssets::scripts();
}
public function dehydrate()
{
static::$hasRenderedAComponentThisRequest = true;
}
static function injectAssets($html, $assetsHead, $assetsBody)
{
$html = str($html);
if ($html->test('/<\s*\/\s*head\s*>/i') && $html->test('/<\s*\/\s*body\s*>/i')) {
return $html
->replaceMatches('/(<\s*\/\s*head\s*>)/i', $assetsHead.'$1')
->replaceMatches('/(<\s*\/\s*body\s*>)/i', $assetsBody.'$1')
->toString();
}
return $html
->replaceMatches('/(<\s*html(?:\s[^>])*>)/i', '$1'.$assetsHead)
->replaceMatches('/(<\s*\/\s*html\s*>)/i', $assetsBody.'$1')
->toString();
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace Livewire\Features\SupportBladeAttributes;
use Livewire\WireDirective;
use Illuminate\View\ComponentAttributeBag;
use Livewire\ComponentHook;
class SupportBladeAttributes extends ComponentHook
{
static function provide()
{
ComponentAttributeBag::macro('wire', function ($name) {
$entries = head((array) $this->whereStartsWith('wire:'.$name));
$directive = head(array_keys($entries));
$value = head(array_values($entries));
return new WireDirective($name, $directive, $value);
});
}
}

View file

@ -0,0 +1,8 @@
<html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
{{ $slot }}
</body>
</html>

View file

@ -0,0 +1,82 @@
<?php
namespace Livewire\Features\SupportChecksumErrorDebugging;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\File;
class SupportChecksumErrorDebugging
{
function boot()
{
// @todo: dont write to this file unless the command is running...
return;
$file = storage_path('framework/cache/lw-checksum-log.json');
Artisan::command('livewire:monitor-checksum', function () use ($file) {
File::put($file, json_encode(['checksums' => [], 'failure' => null]));
$this->info('Monitoring for checksum errors...');
while (true) {
$cache = json_decode(File::get($file), true);
if ($cache['failure']) {
$this->info('Failure: '.$cache['failure']);
$cache['failure'] = null;
}
File::put($file, json_encode($cache));
sleep(1);
}
})->purpose('Debug checksum errors in Livewire');
on('checksum.fail', function ($checksum, $comparitor, $tamperedSnapshot) use ($file) {
$cache = json_decode(File::get($file), true);
if (! isset($cache['checksums'][$checksum])) return;
$canonicalSnapshot = $cache['checksums'][$checksum];
$good = $this->array_diff_assoc_recursive($canonicalSnapshot, $tamperedSnapshot);
$bad = $this->array_diff_assoc_recursive($tamperedSnapshot, $canonicalSnapshot);
$cache['failure'] = "\nBefore: ".json_encode($good)."\nAfter: ".json_encode($bad);
File::put($file, json_encode($cache));
});
on('checksum.generate', function ($checksum, $snapshot) use ($file) {
$cache = json_decode(File::get($file), true);
$cache['checksums'][$checksum] = $snapshot;
File::put($file, json_encode($cache));
});
}
// https://www.php.net/manual/en/function.array-diff-assoc.php#111675
function array_diff_assoc_recursive($array1, $array2) {
$difference=array();
foreach($array1 as $key => $value) {
if( is_array($value) ) {
if( !isset($array2[$key]) || !is_array($array2[$key]) ) {
$difference[$key] = $value;
} else {
$new_diff = $this->array_diff_assoc_recursive($value, $array2[$key]);
if( !empty($new_diff) )
$difference[$key] = $new_diff;
}
} else if( !array_key_exists($key,$array2) || $array2[$key] !== $value ) {
$difference[$key] = $value;
}
}
return $difference;
}
}

View file

@ -0,0 +1,191 @@
<?php
namespace Livewire\Features\SupportCompiledWireKeys;
use Illuminate\Support\Facades\Blade;
use Livewire\ComponentHook;
use function Livewire\on;
class SupportCompiledWireKeys extends ComponentHook
{
public static $loopStack = [];
public static $currentLoop = [
'count' => null,
'index' => null,
'key' => null,
];
public static function provide()
{
on('flush-state', function () {
static::$loopStack = [];
static::$currentLoop = [
'count' => null,
'index' => null,
'key' => null,
];
});
if (! config('livewire.smart_wire_keys', true)) {
return;
}
static::registerPrecompilers();
}
public static function registerPrecompilers()
{
Blade::precompiler(function ($contents) {
$contents = static::compile($contents);
return $contents;
});
}
public static function compile($contents)
{
// Strip out all livewire tag components as we don't want to match any of them...
$placeholder = '<__livewire-component-placeholder__>';
$cleanedContents = preg_replace('/<livewire:[^>]+?\/>/is', $placeholder, $contents);
// Handle `wire:key` attributes on elements...
preg_match_all('/(?<=\s)wire:key\s*=\s*(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\')/', $cleanedContents, $keys);
foreach ($keys[0] as $index => $key) {
$keyExpression = static::compileKeyExpression($keys[1][$index]);
$prefix = "<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::\$currentLoop['key'] = {$keyExpression}; ?>";
$contents = str_replace($key, $prefix . $key, $contents);
}
// Handle `wire:key` attributes on Blade components...
$contents = preg_replace(
'/(<\?php\s+\$component->withAttributes\(\[.*?\]\);\s*\?>)/s',
"$1\n<?php \Livewire\Features\SupportCompiledWireKeys\SupportCompiledWireKeys::processComponentKey(\$component); ?>\n",
$contents
);
return $contents;
}
public static function openLoop() {
if (static::$currentLoop['count'] === null) {
static::$currentLoop['count'] = 0;
} else {
static::$currentLoop['count']++;
}
static::$loopStack[] = static::$currentLoop;
static::$currentLoop = [
'count' => null,
'index' => null,
'key' => null,
];
}
// Increment the loop index for the current iteration. This mirrors how
// Laravel's Blade `$__env->incrementLoopIndices()` works for `@foreach`,
// but without depending on the `$loop` variable (which doesn't exist
// for `@for` and `@while` loops)...
public static function startLoopIteration() {
if (static::$currentLoop['index'] === null) {
static::$currentLoop['index'] = 0;
} else {
static::$currentLoop['index']++;
}
}
/**
* @deprecated Use startLoopIteration() instead. Kept for cached compiled views.
*/
public static function startLoop($index) {
static::$currentLoop['index'] = $index;
}
public static function endLoop() {
static::$currentLoop = [
'count' => null,
'index' => static::$currentLoop['index'] ?? null,
'key' => null,
];
}
public static function closeLoop() {
static::$currentLoop = array_pop(static::$loopStack);
}
public static function compileKeyExpression($keyString)
{
// Compile Blade echo statements into PHP string concatenation
// (mirrors Laravel's ComponentTagCompiler::compileAttributeEchos approach)...
$value = Blade::compileEchos($keyString);
// Escape single quotes only outside of PHP blocks...
$value = collect(token_get_all('<'.'?php ?'.'>'.$value))
->slice(2)
->map(function ($token) {
if (! is_array($token)) {
return $token;
}
return $token[0] === T_INLINE_HTML
? str_replace("'", "\\'", $token[1])
: $token[1];
})->implode('');
$value = str_replace('<'.'?php echo ', "'.", $value);
$value = str_replace('; ?'.'>', ".'", $value);
return "'".$value."'";
}
/**
* Backward-compatibility shim for cached compiled Blade views that still
* reference this method from before the smart keys optimisation in v4.2.
*
* TODO: Remove in v5.
*/
public static function processElementKey($keyString, $data)
{
if (view()->exists($keyString)) {
$key = $keyString;
} else {
$key = Blade::render($keyString, $data);
}
static::$currentLoop['key'] = $key;
}
public static function processComponentKey($component)
{
if ($component->attributes->has('wire:key')) {
static::$currentLoop['key'] = $component->attributes->get('wire:key');
}
}
public static function generateKey($deterministicBladeKey, $key = null)
{
$finalKey = $deterministicBladeKey;
$loops = array_merge(static::$loopStack, [static::$currentLoop]);
foreach ($loops as $loop) {
if (isset($loop['key']) || isset($loop['index'])) {
$finalKey .= isset($loop['key'])
? '-' . $loop['key']
: '-' . $loop['index'];
}
if (isset($loop['count'])) {
$finalKey .= '-' . $loop['count'];
}
}
if (isset($key) && $key !== '') {
$finalKey .= '-' . $key;
}
return $finalKey;
}
}

View file

@ -0,0 +1,175 @@
<?php
namespace Livewire\Features\SupportComputed;
use function Livewire\invade;
use Livewire\Features\SupportAttributes\Attribute;
use Illuminate\Support\Facades\Cache;
#[\Attribute]
class BaseComputed extends Attribute
{
protected $requestCachedValue;
function __construct(
public $persist = false,
public $seconds = 3600, // 1 hour...
public $cache = false,
public $key = null,
public $tags = null,
) {}
function call()
{
throw new CannotCallComputedDirectlyException(
$this->component->getName(),
$this->getName(),
);
}
public function handleMagicGet($returnValue)
{
if ($this->persist) {
$returnValue(
$this->requestCachedValue ??= $this->handlePersistedGet()
);
return;
}
if ($this->cache) {
$returnValue(
$this->requestCachedValue ??= $this->handleCachedGet()
);
return;
}
$returnValue(
$this->requestCachedValue ??= $this->evaluateComputed()
);
}
public function handleMagicUnset()
{
if ($this->persist) {
$this->handlePersistedUnset();
unset($this->requestCachedValue);
return;
}
if ($this->cache) {
$this->handleCachedUnset();
unset($this->requestCachedValue);
return;
}
unset($this->requestCachedValue);
}
protected function handlePersistedGet()
{
$key = $this->generatePersistedKey();
$closure = fn () => $this->evaluateComputed();
$value = match(Cache::supportsTags() && !empty($this->tags)) {
true => Cache::tags($this->tags)->remember($key, $this->seconds, $closure),
default => Cache::remember($key, $this->seconds, $closure)
};
return $this->resolveCachedValue($value, $closure);
}
protected function handleCachedGet()
{
$key = $this->generateCachedKey();
$closure = fn () => $this->evaluateComputed();
$value = match(Cache::supportsTags() && !empty($this->tags)) {
true => Cache::tags($this->tags)->remember($key, $this->seconds, $closure),
default => Cache::remember($key, $this->seconds, $closure)
};
return $this->resolveCachedValue($value, $closure);
}
protected function resolveCachedValue($value, $closure)
{
$class = $this->findIncompleteClass($value);
if ($class === null) return $value;
if (config('app.debug')) {
logger()->warning(
"Livewire re-evaluated cached computed property [{$this->component->getName()}::{$this->getName()}] because Laravel could not unserialize [{$class}]. The value is correct, but it was not served from cache. Return a scalar or array, or add the class to [cache.serializable_classes]."
);
}
return $closure();
}
protected function findIncompleteClass($value)
{
if ($value instanceof \__PHP_Incomplete_Class) {
return ((array) $value)['__PHP_Incomplete_Class_Name'] ?? \__PHP_Incomplete_Class::class;
}
if (! is_array($value)) return null;
foreach ($value as $item) {
if ($class = $this->findIncompleteClass($item)) return $class;
}
return null;
}
protected function handlePersistedUnset()
{
$key = $this->generatePersistedKey();
Cache::forget($key);
}
protected function handleCachedUnset()
{
$key = $this->generateCachedKey();
Cache::forget($key);
}
protected function generatePersistedKey()
{
if ($this->key) return $this->key;
return 'lw_computed.'.$this->component->getId().'.'.$this->getName();
}
protected function generateCachedKey()
{
if ($this->key) return $this->key;
return 'lw_computed.'.$this->component->getName().'.'.$this->getName();
}
protected function evaluateComputed()
{
return invade($this->component)->{parent::getName()}();
}
public function getName()
{
return $this->generatePropertyName(parent::getName());
}
private function generatePropertyName($value)
{
return str($value)->camel()->toString();
}
}

View file

@ -0,0 +1,15 @@
<?php
namespace Livewire\Features\SupportComputed;
use Exception;
class CannotCallComputedDirectlyException extends Exception
{
function __construct($componentName, $methodName)
{
parent::__construct(
"Cannot call [{$methodName}()] computed property method directly on component: {$componentName}"
);
}
}

View file

@ -0,0 +1,119 @@
<?php
namespace Livewire\Features\SupportComputed;
use Livewire\ComponentHook;
use Livewire\Drawer\Utils as SyntheticUtils;
use function Livewire\on;
use function Livewire\store;
use function Livewire\wrap;
class SupportLegacyComputedPropertySyntax extends ComponentHook
{
protected static array $computedPropertyNamesCache = [];
static function provide()
{
on('__get', function ($target, $property, $returnValue) {
// Handle #[Computed] attribute properties (takes priority over legacy)...
$attribute = static::findComputedAttribute($target, $property);
if ($attribute) {
$attribute->handleMagicGet($returnValue);
return;
}
// Handle legacy computed properties (getXxxProperty pattern)...
if (static::hasComputedProperty($target, $property)) {
$returnValue(static::getComputedProperty($target, $property));
}
});
on('__unset', function ($target, $property) {
// Handle #[Computed] attribute properties (takes priority over legacy)...
$attribute = static::findComputedAttribute($target, $property);
if ($attribute) {
$attribute->handleMagicUnset();
return;
}
// Handle legacy computed properties (getXxxProperty pattern)...
if (static::hasComputedProperty($target, $property)) {
store($target)->unset('computedProperties', $property);
}
});
on('flush-state', function () {
static::$computedPropertyNamesCache = [];
});
}
public static function findComputedAttribute($target, $property)
{
$propertyName = (string) str($property)->camel();
return $target->getAttributes()
->whereInstanceOf(BaseComputed::class)
->first(fn ($attr) => $attr->getName() === $propertyName);
}
public static function getComputedProperties($target)
{
return collect(static::getComputedPropertyNames($target))
->mapWithKeys(function ($property) use ($target) {
return [$property => static::getComputedProperty($target, $property)];
})
->all();
}
public static function hasComputedProperty($target, $property)
{
return in_array((string) str($property)->camel(), static::getComputedPropertyNames($target), true);
}
public static function getComputedProperty($target, $property)
{
if (! static::hasComputedProperty($target, $property)) {
throw new \Exception('No computed property found: $'.$property);
}
$method = 'get'.str($property)->studly().'Property';
store($target)->push(
'computedProperties',
$value = store($target)->find('computedProperties', $property, fn() => wrap($target)->$method()),
$property,
);
return $value;
}
public static function getComputedPropertyNames($target)
{
$className = get_class($target);
if (isset(static::$computedPropertyNamesCache[$className])) {
return static::$computedPropertyNamesCache[$className];
}
$methodNames = SyntheticUtils::getPublicMethodsDefinedBySubClass($target);
$computedPropertyNames = collect($methodNames)
->filter(function ($method) {
return str($method)->startsWith('get')
&& str($method)->endsWith('Property');
})
->map(function ($method) {
return (string) str($method)->between('get', 'Property')->camel();
})
->all();
static::$computedPropertyNamesCache[$className] = $computedPropertyNames;
return $computedPropertyNames;
}
}

View file

@ -0,0 +1,57 @@
<?php
namespace Livewire\Features\SupportConsoleCommands\Commands;
use Illuminate\Console\GeneratorCommand;
use Illuminate\Support\Facades\File;
use Symfony\Component\Console\Attribute\AsCommand;
#[AsCommand(name: 'livewire:attribute')]
class AttributeCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $signature = 'livewire:attribute {name} {--force}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new Livewire attribute class';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Attribute';
/**
* Get the stub file for the generator.
*
* @return string
*/
public function getStub()
{
if (File::exists(base_path('stubs/livewire.attribute.stub'))) {
return base_path('stubs/livewire.attribute.stub');
}
return __DIR__ . DIRECTORY_SEPARATOR . 'livewire.attribute.stub';
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
public function getDefaultNamespace($rootNamespace)
{
return $rootNamespace . '\Livewire\Attributes';
}
}

View file

@ -0,0 +1,19 @@
<?php
namespace Livewire\Features\SupportConsoleCommands\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Console\Attribute\AsCommand;
#[AsCommand(name: 'livewire:config')]
class ConfigCommand extends Command
{
protected $signature = 'livewire:config';
protected $description = 'Publish Livewire config file';
public function handle()
{
$this->call('vendor:publish', ['--tag' => 'livewire:config', '--force' => true]);
}
}

View file

@ -0,0 +1,275 @@
<?php
namespace Livewire\Features\SupportConsoleCommands\Commands;
use function Laravel\Prompts\confirm;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Attribute\AsCommand;
use Livewire\Finder\Finder;
use Livewire\Compiler\Parser\SingleFileParser;
use Livewire\Compiler\Parser\MultiFileParser;
use Illuminate\Support\Str;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Console\Command;
#[AsCommand(name: 'livewire:convert')]
class ConvertCommand extends Command
{
protected $name = 'livewire:convert';
protected $description = 'Convert a Livewire component between single-file and multi-file formats';
protected Filesystem $files;
protected Finder $finder;
public function __construct()
{
parent::__construct();
$this->files = app('files');
$this->finder = app('livewire.finder');
}
public function handle()
{
$name = $this->argument('name');
if (! $name) {
$this->components->error('Component name is required.');
return 1;
}
$name = $this->normalizeComponentName($name);
// Detect what type the component currently is
$sfcPath = $this->finder->resolveSingleFileComponentPath($name);
$mfcPath = $this->finder->resolveMultiFileComponentPath($name);
$isSfc = $sfcPath && $this->files->exists($sfcPath);
$isMfc = $mfcPath && $this->files->exists($mfcPath) && $this->files->isDirectory($mfcPath);
if (! $isSfc && ! $isMfc) {
$this->components->error('Component not found.');
return 1;
}
if ($isSfc && $isMfc) {
$this->components->error('Component exists in both single-file and multi-file formats. Please resolve this conflict first.');
return 1;
}
// Determine target format
$targetFormat = $this->determineTargetFormat($isSfc);
if ($targetFormat === 'mfc' && $isSfc) {
return $this->convertSingleFileToMultiFile($name, $sfcPath);
}
if ($targetFormat === 'sfc' && $isMfc) {
return $this->convertMultiFileToSingleFile($name, $mfcPath);
}
$this->components->error('Component is already in the target format.');
return 1;
}
protected function normalizeComponentName(string $name): string
{
return (string) str($name)
->replace('/', '.')
->replace('\\', '.')
->explode('.')
->map(fn ($i) => str($i)->kebab())
->implode('.');
}
protected function determineTargetFormat(bool $isSfc): string
{
if ($this->option('mfc')) {
return 'mfc';
}
if ($this->option('sfc')) {
return 'sfc';
}
// If no option specified, auto-detect and convert to opposite
return $isSfc ? 'mfc' : 'sfc';
}
public function convertSingleFileToMultiFile(string $name, string $sfcPath): int
{
// Use the SFC filename (without .blade.php) as the directory name
// This ensures we preserve emoji/naming exactly as it exists
$sfcFilename = basename($sfcPath);
$directoryName = str_replace('.blade.php', '', $sfcFilename);
$directory = dirname($sfcPath) . '/' . $directoryName;
// Component name for files inside the directory (without emoji)
$componentName = str_replace(['⚡', '⚡︎', '⚡️'], '', $directoryName);
$classPath = $directory . '/' . $componentName . '.php';
$viewPath = $directory . '/' . $componentName . '.blade.php';
$testPath = $directory . '/' . $componentName . '.test.php';
$jsPath = $directory . '/' . $componentName . '.js';
$cssPath = $directory . '/' . $componentName . '.css';
$globalCssPath = $directory . '/' . $componentName . '.global.css';
$parser = SingleFileParser::parse(app('livewire.compiler'), $sfcPath);
$this->ensureDirectoryExists($directory);
$scriptContents = $parser->generateScriptContentsForMultiFile();
$styleContents = $parser->generateStyleContentsForMultiFile();
$globalStyleContents = $parser->generateGlobalStyleContentsForMultiFile();
$classContents = $parser->generateClassContentsForMultiFile();
$viewContents = $parser->generateViewContentsForMultiFile();
$this->files->put($classPath, $classContents);
$this->files->put($viewPath, $viewContents);
// Check for existing test file next to SFC
$sfcTestPath = str_replace('.blade.php', '.test.php', $sfcPath);
$existingTestFile = $this->files->exists($sfcTestPath);
if ($existingTestFile) {
// Move existing test file into MFC directory
$testContents = $this->files->get($sfcTestPath);
$this->files->put($testPath, $testContents);
$this->files->delete($sfcTestPath);
} elseif ($this->option('test')) {
// Create new test file if --test flag passed and no existing test
$this->files->put($testPath, $this->buildMultiFileComponentTest($name));
}
if ($scriptContents !== null) {
$this->files->put($jsPath, $scriptContents);
}
if ($styleContents !== null) {
$this->files->put($cssPath, $styleContents);
}
if ($globalStyleContents !== null) {
$this->files->put($globalCssPath, $globalStyleContents);
}
$this->files->delete($sfcPath);
$this->components->info(sprintf('Livewire component [%s] converted to multi-file successfully.', $directory));
return 0;
}
public function convertMultiFileToSingleFile(string $name, string $mfcPath): int
{
// Use the MFC directory name as the SFC filename (with .blade.php)
// This ensures we preserve emoji/naming exactly as it exists
$directoryName = basename($mfcPath);
$sfcPath = dirname($mfcPath) . '/' . $directoryName . '.blade.php';
// Component name for files inside the directory (without emoji)
$componentName = str_replace(['⚡', '⚡︎', '⚡️'], '', $directoryName);
$classPath = $mfcPath . '/' . $componentName . '.php';
$viewPath = $mfcPath . '/' . $componentName . '.blade.php';
$testPath = $mfcPath . '/' . $componentName . '.test.php';
$jsPath = $mfcPath . '/' . $componentName . '.js';
if (! $this->files->exists($classPath)) {
$this->components->error('Multi-file component class file not found.');
return 1;
}
if (! $this->files->exists($viewPath)) {
$this->components->error('Multi-file component view file not found.');
return 1;
}
$testFileExists = $this->files->exists($testPath);
$parser = MultiFileParser::parse(app('livewire.compiler'), $mfcPath);
// Generate the single-file component contents
$sfcContents = $parser->generateContentsForSingleFile();
$this->ensureDirectoryExists(dirname($sfcPath));
$this->files->put($sfcPath, $sfcContents);
// Move test file out before deleting directory
if ($testFileExists) {
$testContents = $this->files->get($testPath);
$sfcTestPath = str_replace('.blade.php', '.test.php', $sfcPath);
$this->files->put($sfcTestPath, $testContents);
}
// Delete the multi-file directory
$this->files->deleteDirectory($mfcPath);
$this->components->info(sprintf('Livewire component [%s] converted to single-file successfully.', $sfcPath));
return 0;
}
protected function buildMultiFileComponentTest(string $name): string
{
$stub = $this->files->get($this->getStubPath('livewire-mfc-test.stub'));
$componentName = collect(explode('.', $name))
->map(fn ($segment) => Str::kebab($segment))
->implode('.');
$stub = str_replace('[component-name]', $componentName, $stub);
return $stub;
}
protected function getStubPath(string $stub): string
{
$customPath = $this->laravel->basePath('stubs/' . $stub);
if ($this->files->exists($customPath)) {
return $customPath;
}
// Look for the stub in the MakeCommand directory
return dirname(__FILE__) . '/' . $stub;
}
protected function ensureDirectoryExists(string $path): void
{
if (! $this->files->isDirectory($path)) {
$this->files->makeDirectory($path, 0755, true, true);
}
}
protected function shouldUseEmoji(): bool
{
if ($this->option('emoji') !== null) {
return filter_var($this->option('emoji'), FILTER_VALIDATE_BOOLEAN);
}
return config('livewire.make_command.emoji', true);
}
protected function getArguments()
{
return [
['name', InputArgument::REQUIRED, 'The name of the component'],
];
}
protected function getOptions()
{
return [
['sfc', null, InputOption::VALUE_NONE, 'Convert to single-file component'],
['mfc', null, InputOption::VALUE_NONE, 'Convert to multi-file component'],
['test', null, InputOption::VALUE_NONE, 'Create a test file when converting to multi-file (if one does not exist)'],
['emoji', null, InputOption::VALUE_REQUIRED, 'Use emoji in file/directory names (true or false)'],
];
}
}

View file

@ -0,0 +1,45 @@
<?php
namespace Livewire\Features\SupportConsoleCommands\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use function Livewire\str;
class FileManipulationCommand extends Command
{
protected $parser;
protected function ensureDirectoryExists($path)
{
if (! File::isDirectory(dirname($path))) {
File::makeDirectory(dirname($path), 0777, $recursive = true, $force = true);
}
}
public function isFirstTimeMakingAComponent()
{
$namespace = str(config('livewire.class_namespace'))->replaceFirst(app()->getNamespace(), '');
$livewireFolder = app_path($namespace->explode('\\')->implode(DIRECTORY_SEPARATOR));
return ! File::isDirectory($livewireFolder);
}
public function writeWelcomeMessage()
{
$asciiLogo = <<<EOT
<fg=magenta> _._</>
<fg=magenta>/ /<fg=white>o</>\ \ </> <fg=cyan> || () () __ </>
<fg=magenta>|_\ /_|</> <fg=cyan> || || \\\// /_\ \\\ // || |~~ /_\ </>
<fg=magenta> <fg=cyan>|</>`<fg=cyan>|</>`<fg=cyan>|</> </> <fg=cyan> || || \/ \\\_ \^/ || || \\\_ </>
EOT;
// _._
// / /o\ \ || () () __
// |_\ /_| || || \\\// /_\ \\\ // || |~~ /_\
// |`|`| || || \/ \\\_ \^/ || || \\\_
$this->line("\n".$asciiLogo."\n");
$this->line("\n<options=bold>Congratulations, you've created your first Livewire component!</> 🎉🎉🎉\n");
}
}

View file

@ -0,0 +1,57 @@
<?php
namespace Livewire\Features\SupportConsoleCommands\Commands;
use Illuminate\Console\GeneratorCommand;
use Illuminate\Support\Facades\File;
use Symfony\Component\Console\Attribute\AsCommand;
#[AsCommand(name: 'livewire:form')]
class FormCommand extends GeneratorCommand
{
/**
* The console command name.
*
* @var string
*/
protected $signature = 'livewire:form {name} {--force}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a new Livewire form class';
/**
* The type of class being generated.
*
* @var string
*/
protected $type = 'Form';
/**
* Get the stub file for the generator.
*
* @return string
*/
public function getStub()
{
if (File::exists(base_path('stubs/livewire.form.stub'))) {
return base_path('stubs/livewire.form.stub');
}
return __DIR__ . DIRECTORY_SEPARATOR . 'livewire.form.stub';
}
/**
* Get the default namespace for the class.
*
* @param string $rootNamespace
* @return string
*/
public function getDefaultNamespace($rootNamespace)
{
return $rootNamespace . '\Livewire\Forms';
}
}

View file

@ -0,0 +1,100 @@
<?php
namespace Livewire\Features\SupportConsoleCommands\Commands;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
use Symfony\Component\Console\Attribute\AsCommand;
#[AsCommand(name: 'livewire:layout')]
class LayoutCommand extends FileManipulationCommand
{
protected $signature = 'livewire:layout {--force} {--stub= : If you have several stubs, stored in subfolders }';
protected $description = 'Create a new app layout file';
public function handle()
{
$baseViewPath = resource_path('views');
$layout = str(config('livewire.component_layout'));
$layoutPath = $this->layoutPath($baseViewPath, $layout);
$relativeLayoutPath = $this->relativeLayoutPath($layoutPath);
$force = $this->option('force');
$stubPath = $this->stubPath($this->option('stub'));
if (File::exists($layoutPath) && ! $force) {
$this->line("<fg=red;options=bold>View already exists:</> {$relativeLayoutPath}");
return false;
}
$this->ensureDirectoryExists($layoutPath);
$result = File::copy($stubPath, $layoutPath);
if ($result) {
$this->line("<options=bold,reverse;fg=green> LAYOUT CREATED </> 🤙\n");
$this->line("<options=bold;fg=green>CLASS:</> {$relativeLayoutPath}");
}
}
protected function stubPath($stubSubDirectory = '')
{
$stubName = 'livewire.layout.stub';
if (! empty($stubSubDirectory) && str($stubSubDirectory)->startsWith('..')) {
$stubDirectory = rtrim(str($stubSubDirectory)->replaceFirst('..' . DIRECTORY_SEPARATOR, ''), DIRECTORY_SEPARATOR) . '/';
} else {
$stubDirectory = rtrim('stubs' . DIRECTORY_SEPARATOR . $stubSubDirectory, DIRECTORY_SEPARATOR) . '/';
}
if (File::exists($stubPath = base_path($stubDirectory . $stubName))) {
return $stubPath;
}
return __DIR__ . DIRECTORY_SEPARATOR . $stubName;
}
protected function layoutPath($baseViewPath, $layout)
{
// Handle namespaced views like 'layouts::app'
if ($layout->contains('::')) {
[$namespace, $name] = $layout->explode('::');
// Check if this namespace is registered in Livewire config
$namespacePath = config("livewire.component_namespaces.{$namespace}");
if ($namespacePath) {
// Use the configured namespace path
$baseViewPath = $namespacePath;
} else {
// Default to resources/views/{namespace}
$baseViewPath = resource_path("views/{$namespace}");
}
// Now process the name part (e.g., 'app' or 'admin.dashboard')
$directories = str($name)->explode('.');
} else {
// Non-namespaced view, process normally
$directories = $layout->explode('.');
}
$name = Str::kebab($directories->pop());
return $baseViewPath . DIRECTORY_SEPARATOR . collect()
->concat($directories)
->map([Str::class, 'kebab'])
->push("{$name}.blade.php")
->implode(DIRECTORY_SEPARATOR);
}
protected function relativeLayoutPath($layoutPath)
{
return (string) str($layoutPath)->replaceFirst(base_path() . '/', '');
}
}

View file

@ -0,0 +1,13 @@
<?php
namespace Livewire\Features\SupportConsoleCommands\Commands;
use Symfony\Component\Console\Attribute\AsCommand;
#[AsCommand(name: 'livewire:make')]
class LivewireMakeCommand extends MakeCommand
{
protected $name = 'livewire:make';
protected $hidden = true; // Hide from command list to avoid duplication
}

View file

@ -0,0 +1,605 @@
<?php
namespace Livewire\Features\SupportConsoleCommands\Commands;
use function Laravel\Prompts\text;
use function Laravel\Prompts\confirm;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Attribute\AsCommand;
use Livewire\Finder\Finder;
use Livewire\Compiler\Parser\SingleFileParser;
use Livewire\Compiler\Compiler;
use Illuminate\Support\Str;
use Illuminate\Foundation\Inspiring;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Console\Command;
#[AsCommand(name: 'make:livewire')]
class MakeCommand extends Command
{
protected $name = 'make:livewire';
protected $description = 'Create a new Livewire component';
protected Filesystem $files;
protected Finder $finder;
protected Compiler $compiler;
public function __construct()
{
parent::__construct();
$this->files = app('files');
$this->finder = app('livewire.finder');
$this->compiler = app('livewire.compiler');
}
public function handle()
{
$name = $this->argument('name');
if (! $name) {
$name = text('What should the component be named?', required: true);
}
$name = $this->normalizeComponentName($name);
// If --test flag is provided and component already exists, just create the test
if ($this->option('test') && $this->componentExistsInAnyForm($name)) {
return $this->createTestForExistingComponent($name);
}
// Check if component already exists in ANY form before proceeding
if ($this->componentExistsInAnyForm($name)) {
$this->components->error('Component already exists.');
return 1;
}
$type = $this->determineComponentType(
config('livewire.make_command.type', 'sfc'),
);
switch ($type) {
case 'class':
return $this->createClassBasedComponent($name);
case 'mfc':
return $this->createMultiFileComponent($name);
case 'sfc':
default:
return $this->createSingleFileComponent($name);
}
}
protected function normalizeComponentName(string $name): string
{
return (string) str($name)
->replace('/', '.')
->replace('\\', '.')
->explode('.')
->map(fn ($i) => str($i)->kebab())
->implode('.');
}
protected function determineComponentType($fallback): string
{
if ($this->option('class')) {
return 'class';
}
if ($this->option('mfc')) {
return 'mfc';
}
if ($this->option('sfc')) {
return 'sfc';
}
if ($this->option('type')) {
return $this->option('type');
}
return $fallback;
}
protected function createClassBasedComponent(string $name): int
{
[$namespace, $componentName] = $this->finder->parseNamespaceAndName($name);
if ($namespace !== null) {
$classNamespaceDetails = $this->finder->getClassNamespace($namespace);
if ($classNamespaceDetails === null) {
$this->components->error(sprintf('Class namespace [%s] not found.', $namespace));
return 1;
}
} else {
$classNamespaceDetails = null;
}
$paths = $this->finder->resolveClassComponentFilePaths($name);
$this->ensureDirectoryExists(dirname($paths['class']));
$this->ensureDirectoryExists(dirname($paths['view']));
$classContent = $this->buildClassBasedComponentClass($componentName, $classNamespaceDetails);
$viewContent = $this->buildClassBasedComponentView();
$this->files->put($paths['class'], $classContent);
$this->files->put($paths['view'], $viewContent);
// Create test file if --test flag is present or configured in make_command.with.test
if ($this->option('test') || config('livewire.make_command.with.test')) {
$testPath = $this->getClassBasedComponentTestPath($name);
$this->ensureDirectoryExists(dirname($testPath));
$testContent = $this->buildClassBasedComponentTest($name);
$this->files->put($testPath, $testContent);
}
$this->components->info(sprintf('Livewire component [%s] created successfully.', $paths['class']));
return 0;
}
protected function createSingleFileComponent(string $name): int
{
$path = $this->finder->resolveSingleFileComponentPathForCreation($name, $this->shouldUseEmoji());
if ($path === null) {
[$namespace] = $this->finder->parseNamespaceAndName($name);
$this->components->error(sprintf(
"Namespace [%s] is not registered. Register it in config/livewire.php under 'component_namespaces' or use Livewire::addNamespace() in a service provider.",
$namespace
));
return 1;
}
// Check if we're converting from a multi-file component
$mfcPath = $this->finder->resolveMultiFileComponentPath($name);
if ($mfcPath && $this->files->exists($mfcPath) && $this->files->isDirectory($mfcPath)) {
// Skip interactive prompts in testing environment
if (app()->runningUnitTests()) {
$this->components->error('Component already exists.');
return 1;
}
$convert = confirm('Component already exists as a multi-file component. Would you like to convert it to a single-file component?');
if ($convert) {
return $this->call('livewire:convert', ['name' => $name, '--sfc' => true]);
}
$this->components->error('Component already exists.');
return 1;
}
if ($this->files->exists($path)) {
// Skip interactive prompts in testing environment
if (app()->runningUnitTests()) {
$this->components->error('Component already exists.');
return 1;
}
$upgrade = confirm('Component already exists. Would you like to upgrade this component to a multi-file component?');
if ($upgrade) {
return $this->call('livewire:convert', ['name' => $name, '--mfc' => true]);
}
$this->components->error('Component already exists.');
return 1;
}
$this->ensureDirectoryExists(dirname($path));
$content = $this->buildSingleFileComponent();
$this->files->put($path, $content);
// Create test file if --test flag is present or configured in make_command.with.test
if ($this->option('test') || config('livewire.make_command.with.test')) {
$testPath = $this->getSingleFileComponentTestPath($path);
$testContent = $this->buildSingleFileComponentTest($name);
$this->files->put($testPath, $testContent);
}
$this->components->info(sprintf('Livewire component [%s] created successfully.', $path));
return 0;
}
protected function createMultiFileComponent(string $name): int
{
$directory = $this->finder->resolveMultiFileComponentPathForCreation($name, $this->shouldUseEmoji());
if ($directory === null) {
[$namespace] = $this->finder->parseNamespaceAndName($name);
$this->components->error(sprintf(
"Namespace [%s] is not registered. Register it in config/livewire.php under 'component_namespaces' or use Livewire::addNamespace() in a service provider.",
$namespace
));
return 1;
}
// Get the component name without emoji for file names inside the directory
$componentName = basename($directory);
if ($this->shouldUseEmoji()) {
$componentName = str_replace(['⚡', '⚡︎', '⚡️'], '', $componentName);
}
// Define file paths
$classPath = $directory . '/' . $componentName . '.php';
$viewPath = $directory . '/' . $componentName . '.blade.php';
$testPath = $directory . '/' . $componentName . '.test.php';
$jsPath = $directory . '/' . $componentName . '.js';
$cssPath = $directory . '/' . $componentName . '.css';
// Check if we're upgrading from a single-file component
$sfcPath = $this->finder->resolveSingleFileComponentPathForCreation($name, $this->shouldUseEmoji());
if ($this->files->exists($sfcPath)) {
// Skip interactive prompts in testing environment
if (app()->runningUnitTests()) {
$this->components->error('Component already exists.');
return 1;
}
$upgrade = confirm('Component already exists as a single-file component. Would you like to upgrade it to a multi-file component?');
if ($upgrade) {
return $this->call('livewire:convert', ['name' => $name, '--mfc' => true]);
}
$this->components->error('Component already exists.');
return 1;
}
if ($this->files->exists($directory)) {
$this->components->error('Component already exists.');
return 1;
}
$this->ensureDirectoryExists($directory);
$classContent = $this->buildMultiFileComponentClass();
$viewContent = $this->buildMultiFileComponentView();
$testContent = $this->buildMultiFileComponentTest($name);
$jsContent = $this->buildMultiFileComponentJs();
$this->files->put($classPath, $classContent);
$this->files->put($viewPath, $viewContent);
if ($this->option('test') || config('livewire.make_command.with.test')) {
$this->files->put($testPath, $testContent);
}
if ($this->option('js') || config('livewire.make_command.with.js')) {
$this->files->put($jsPath, $jsContent);
}
if ($this->option('css') || config('livewire.make_command.with.css')) {
$cssContent = $this->buildMultiFileComponentCss();
$this->files->put($cssPath, $cssContent);
}
$this->components->info(sprintf('Livewire component [%s] created successfully.', $directory));
return 0;
}
protected function shouldUseEmoji(): bool
{
if ($this->option('emoji') !== null) {
return filter_var($this->option('emoji'), FILTER_VALIDATE_BOOLEAN);
}
return config('livewire.make_command.emoji', true);
}
protected function buildClassBasedComponentClass(string $componentName, ?array $classNamespaceDetails = null): string
{
$stub = $this->files->get($this->getStubPath('livewire.stub'));
$segments = explode('.', $componentName);
$className = Str::studly(end($segments));
$namespaceSegments = array_slice($segments, 0, -1);
if ($classNamespaceDetails !== null) {
$namespace = $classNamespaceDetails['classNamespace'];
$viewPath = $classNamespaceDetails['classViewPath'];
} else {
$namespace = config('livewire.class_namespace', 'App\\Livewire');
$viewPath = config('livewire.view_path', resource_path('views/livewire'));
}
if (! empty($namespaceSegments)) {
$namespace .= '\\' . collect($namespaceSegments)
->map(fn($segment) => Str::studly($segment))
->implode('\\');
}
// Get the configured view path and extract the view namespace from it
$viewNamespace = $this->extractViewNamespace($viewPath);
$viewName = collect($segments)
->map(fn($segment) => Str::kebab($segment))
->prepend($viewNamespace)
->filter()
->implode('.');
$stub = str_replace('[namespace]', $namespace, $stub);
$stub = str_replace('[class]', $className, $stub);
$stub = str_replace('[view]', $viewName, $stub);
return $stub;
}
protected function buildClassBasedComponentView(): string
{
$stub = $this->files->get($this->getStubPath('livewire.view.stub'));
$stub = str_replace('[quote]', Inspiring::quotes()->random(), $stub);
return $stub;
}
protected function buildSingleFileComponent(): string
{
$stub = $this->files->get($this->getStubPath('livewire-sfc.stub'));
$stub = str_replace('[quote]', Inspiring::quotes()->random(), $stub);
return $stub;
}
protected function buildMultiFileComponentClass(): string
{
return $this->files->get($this->getStubPath('livewire-mfc-class.stub'));
}
protected function buildMultiFileComponentView(): string
{
$stub = $this->files->get($this->getStubPath('livewire-mfc-view.stub'));
$stub = str_replace('[quote]', Inspiring::quotes()->random(), $stub);
return $stub;
}
protected function buildMultiFileComponentTest(string $name): string
{
$stub = $this->files->get($this->getStubPath('livewire-mfc-test.stub'));
$componentName = collect(explode('.', $name))
->map(fn($segment) => Str::kebab($segment))
->implode('.');
$stub = str_replace('[component-name]', $componentName, $stub);
return $stub;
}
protected function buildMultiFileComponentJs(): string
{
return $this->files->get($this->getStubPath('livewire-mfc-js.stub'));
}
protected function buildMultiFileComponentCss(): string
{
return $this->files->get($this->getStubPath('livewire-mfc-css.stub'));
}
protected function getSingleFileComponentTestPath(string $sfcPath): string
{
// Convert: /path/⚡foo.blade.php → /path/⚡foo.test.php
return str_replace('.blade.php', '.test.php', $sfcPath);
}
protected function buildSingleFileComponentTest(string $name): string
{
// Use same stub as MFC, same format
$stub = $this->files->get($this->getStubPath('livewire-mfc-test.stub'));
$componentName = collect(explode('.', $name))
->map(fn($segment) => Str::kebab($segment))
->implode('.');
$stub = str_replace('[component-name]', $componentName, $stub);
return $stub;
}
protected function getClassBasedComponentTestPath(string $name): string
{
$segments = explode('.', $name);
$className = Str::studly(end($segments)) . 'Test';
$namespaceSegments = array_slice($segments, 0, -1);
$path = base_path('tests/Feature/Livewire');
if (! empty($namespaceSegments)) {
$path .= '/' . collect($namespaceSegments)
->map(fn($segment) => Str::studly($segment))
->implode('/');
}
return $path . '/' . $className . '.php';
}
protected function buildClassBasedComponentTest(string $name): string
{
// Use same Pest-style stub as MFC/SFC for consistency
$stub = $this->files->get($this->getStubPath('livewire-mfc-test.stub'));
$componentName = collect(explode('.', $name))
->map(fn($segment) => Str::kebab($segment))
->implode('.');
$stub = str_replace('[component-name]', $componentName, $stub);
return $stub;
}
protected function getStubPath(string $stub): string
{
$customPath = $this->laravel->basePath('stubs/' . $stub);
if ($this->files->exists($customPath)) {
return $customPath;
}
return __DIR__ . '/' . $stub;
}
protected function ensureDirectoryExists(string $path): void
{
if (! $this->files->isDirectory($path)) {
$this->files->makeDirectory($path, 0755, true, true);
}
}
protected function extractViewNamespace(string $viewPath): string
{
// Convert the view path to a namespace
// e.g., resource_path('views/livewire') => 'livewire'
// e.g., resource_path('views/not-livewire') => 'not-livewire'
$viewsPath = resource_path('views');
if ($viewPath === $viewsPath) {
return '';
}
// Remove the base views path to get the relative path
$relativePath = str_replace($viewsPath . DIRECTORY_SEPARATOR, '', $viewPath);
$relativePath = str_replace($viewsPath . '/', '', $relativePath);
// Convert directory separators to dots for the namespace
return str_replace(['/', '\\'], '.', $relativePath);
}
protected function componentExistsInAnyForm(string $name): bool
{
$finder = $this->finder;
// Check for multi-file component
$mfcPath = $finder->resolveMultiFileComponentPath($name);
if ($mfcPath && $this->files->exists($mfcPath) && $this->files->isDirectory($mfcPath)) {
return true;
}
// Check for single-file component
$sfcPath = $finder->resolveSingleFileComponentPathForCreation($name, $this->shouldUseEmoji());
if ($sfcPath !== null && $this->files->exists($sfcPath)) {
return true;
}
// Check for class-based component
$paths = $finder->resolveClassComponentFilePaths($name);
if (isset($paths['class']) && $this->files->exists($paths['class'])) {
return true;
}
return false;
}
protected function createTestForExistingComponent(string $name): int
{
$finder = $this->finder;
// Check for multi-file component first
$mfcPath = $finder->resolveMultiFileComponentPath($name);
if ($mfcPath && $this->files->exists($mfcPath) && $this->files->isDirectory($mfcPath)) {
$componentName = basename($mfcPath);
if ($this->shouldUseEmoji()) {
$componentName = str_replace(['⚡', '⚡︎', '⚡️'], '', $componentName);
}
$testPath = $mfcPath . '/' . $componentName . '.test.php';
if ($this->files->exists($testPath)) {
$this->components->error('Test file already exists.');
return 1;
}
$testContent = $this->buildMultiFileComponentTest($name);
$this->files->put($testPath, $testContent);
$this->components->info(sprintf('Livewire test [%s] created successfully.', $testPath));
return 0;
}
// Check for single-file component
$sfcPath = $finder->resolveSingleFileComponentPathForCreation($name, $this->shouldUseEmoji());
if ($sfcPath !== null && $this->files->exists($sfcPath)) {
$testPath = $this->getSingleFileComponentTestPath($sfcPath);
if ($this->files->exists($testPath)) {
$this->components->error('Test file already exists.');
return 1;
}
$testContent = $this->buildSingleFileComponentTest($name);
$this->files->put($testPath, $testContent);
$this->components->info(sprintf('Livewire test [%s] created successfully.', $testPath));
return 0;
}
// Check for class-based component
$paths = $finder->resolveClassComponentFilePaths($name);
if (isset($paths['class']) && $this->files->exists($paths['class'])) {
// For class-based components, create test in tests/Feature/Livewire directory
$testPath = $this->getClassBasedComponentTestPath($name);
$this->ensureDirectoryExists(dirname($testPath));
if ($this->files->exists($testPath)) {
$this->components->error('Test file already exists.');
return 1;
}
$testContent = $this->buildClassBasedComponentTest($name);
$this->files->put($testPath, $testContent);
$this->components->info(sprintf('Livewire test [%s] created successfully.', $testPath));
return 0;
}
$this->components->error('Component not found.');
return 1;
}
protected function getArguments()
{
return [
['name', InputArgument::OPTIONAL, 'The name of the component'],
];
}
protected function getOptions()
{
return [
['sfc', null, InputOption::VALUE_NONE, 'Create a single-file component'],
['mfc', null, InputOption::VALUE_NONE, 'Create a multi-file component'],
['class', null, InputOption::VALUE_NONE, 'Create a class-based component'],
['type', null, InputOption::VALUE_REQUIRED, 'Component type (sfc, mfc, or class)'],
['test', null, InputOption::VALUE_NONE, 'Create a test file'],
['emoji', null, InputOption::VALUE_REQUIRED, 'Use emoji in file/directory names (true or false)'],
['js', null, InputOption::VALUE_NONE, 'Create a JavaScript file for multi-file components'],
['css', null, InputOption::VALUE_NONE, 'Create CSS files for multi-file components'],
];
}
}

View file

@ -0,0 +1,46 @@
<?php
namespace Livewire\Features\SupportConsoleCommands\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Console\Attribute\AsCommand;
#[AsCommand(name: 'livewire:publish')]
class PublishCommand extends Command
{
protected $signature = 'livewire:publish
{ --assets : Indicates if Livewire\'s front-end assets should be published }
{ --config : Indicates if Livewire\'s config file should be published }
{ --pagination : Indicates if Livewire\'s pagination views should be published }';
protected $description = 'Publish Livewire configuration';
public function handle()
{
if ($this->option('assets')) {
$this->publishAssets();
} elseif ($this->option('config')) {
$this->publishConfig();
} elseif ($this->option('pagination')) {
$this->publishPagination();
} else {
$this->publishConfig();
$this->publishPagination();
}
}
public function publishAssets()
{
$this->call('vendor:publish', ['--tag' => 'livewire:assets', '--force' => true]);
}
public function publishConfig()
{
$this->call('vendor:publish', ['--tag' => 'livewire:config', '--force' => true]);
}
public function publishPagination()
{
$this->call('vendor:publish', ['--tag' => 'livewire:pagination', '--force' => true]);
}
}

View file

@ -0,0 +1,98 @@
<?php
namespace Livewire\Features\SupportConsoleCommands\Commands;
use Aws\S3\S3Client;
use function array_merge;
use function Livewire\invade;
use Livewire\Features\SupportFileUploads\FileUploadConfiguration;
use Illuminate\Console\Command;
use Symfony\Component\Console\Attribute\AsCommand;
#[AsCommand(name: 'livewire:configure-s3-upload-cleanup')]
class S3CleanupCommand extends Command
{
protected $signature = 'livewire:configure-s3-upload-cleanup';
protected $description = 'Configure temporary file upload s3 directory to automatically cleanup files older than 24hrs';
public function handle()
{
if (! FileUploadConfiguration::isUsingS3()) {
$this->error("Configuration ['livewire.temporary_file_upload.disk'] is not set to a disk with an S3 driver.");
return;
}
$driver = FileUploadConfiguration::storage()->getDriver();
// Flysystem V2+ doesn't allow direct access to adapter, so we need to invade instead.
$adapter = invade($driver)->adapter;
// Flysystem V2+ doesn't allow direct access to client, so we need to invade instead.
$client = invade($adapter)->client;
// Flysystem V2+ doesn't allow direct access to bucket, so we need to invade instead.
$bucket = invade($adapter)->bucket;
$prefix = FileUploadConfiguration::path();
$rules[] = [
'Filter' => [
'Prefix' => $prefix,
],
'Expiration' => [
'Days' => 1,
],
'Status' => 'Enabled',
];
$rules = $this->mergeRulesWithExistingConfiguration($client, $bucket, $prefix, $rules);
try {
$client->putBucketLifecycleConfiguration([
'Bucket' => $bucket,
'LifecycleConfiguration' => [
'Rules' => $rules
],
]);
} catch (\Exception $e) {
$this->error('Failed to configure S3 bucket ['.$bucket.'] to automatically cleanup files older than 24hrs!');
$this->error($e->getMessage());
return;
}
$this->info('Livewire temporary S3 upload directory ['.$prefix.'] set to automatically cleanup files older than 24hrs!');
}
private function checkIfLivewireConfigurationIsAlreadySet(array $existingConfigurationRules, string $bucket, S3Client $client, string $prefix) {
$existingConfigurationHasLivewire = collect($existingConfigurationRules)->contains('Filter.Prefix', $prefix);
if($existingConfigurationHasLivewire) {
$this->info('Livewire temporary S3 upload directory ['.$prefix.'] already set to automatically cleanup files older than 24hrs!');
$this->info('No changes made to S3 bucket ['.$bucket.'] configuration.');
exit;
}
}
private function mergeRulesWithExistingConfiguration(S3Client $client, string $bucket, string $prefix, array $rules): array
{
try {
$existingConfiguration = $client->getBucketLifecycleConfiguration([
'Bucket' => $bucket,
]);
} catch (\Exception $e) {
// if no configuration exists, we'll just ignore the error and continue.
$existingConfiguration = null;
}
if ($existingConfiguration) {
$this->checkIfLivewireConfigurationIsAlreadySet($existingConfiguration['Rules'], $bucket, $client, $prefix);
$existingConfiguration = $existingConfiguration['Rules'];
$rules = array_merge($existingConfiguration, $rules);
}
return $rules;
}
}

View file

@ -0,0 +1,96 @@
<?php
namespace Livewire\Features\SupportConsoleCommands\Commands;
use Illuminate\Console\Command;
use Illuminate\Filesystem\Filesystem;
use Symfony\Component\Console\Attribute\AsCommand;
#[AsCommand(name: 'livewire:stubs')]
class StubsCommand extends Command
{
protected $signature = 'livewire:stubs';
protected $description = 'Publish Livewire stubs';
protected $parser;
public function handle()
{
if (! is_dir($stubsPath = base_path('stubs'))) {
(new Filesystem)->makeDirectory($stubsPath);
}
file_put_contents(
$stubsPath.'/livewire.stub',
file_get_contents(__DIR__.'/livewire.stub')
);
file_put_contents(
$stubsPath.'/livewire.inline.stub',
file_get_contents(__DIR__.'/livewire.inline.stub')
);
file_put_contents(
$stubsPath.'/livewire.view.stub',
file_get_contents(__DIR__.'/livewire.view.stub')
);
file_put_contents(
$stubsPath.'/livewire.test.stub',
file_get_contents(__DIR__.'/livewire.test.stub')
);
file_put_contents(
$stubsPath.'/livewire.pest.stub',
file_get_contents(__DIR__.'/livewire.pest.stub')
);
file_put_contents(
$stubsPath.'/livewire.form.stub',
file_get_contents(__DIR__.'/livewire.form.stub')
);
file_put_contents(
$stubsPath.'/livewire.attribute.stub',
file_get_contents(__DIR__.'/livewire.attribute.stub')
);
file_put_contents(
$stubsPath.'/livewire.layout.stub',
file_get_contents(__DIR__.'/livewire.layout.stub')
);
file_put_contents(
$stubsPath.'/livewire-sfc.stub',
file_get_contents(__DIR__.'/livewire-sfc.stub')
);
file_put_contents(
$stubsPath.'/livewire-mfc-class.stub',
file_get_contents(__DIR__.'/livewire-mfc-class.stub')
);
file_put_contents(
$stubsPath.'/livewire-mfc-view.stub',
file_get_contents(__DIR__.'/livewire-mfc-view.stub')
);
file_put_contents(
$stubsPath.'/livewire-mfc-test.stub',
file_get_contents(__DIR__.'/livewire-mfc-test.stub')
);
file_put_contents(
$stubsPath.'/livewire-mfc-js.stub',
file_get_contents(__DIR__.'/livewire-mfc-js.stub')
);
file_put_contents(
$stubsPath.'/livewire-mfc-css.stub',
file_get_contents(__DIR__.'/livewire-mfc-css.stub')
);
$this->info('Stubs published successfully.');
}
}

View file

@ -0,0 +1,8 @@
<?php
use Livewire\Component;
new class extends Component
{
//
};

View file

@ -0,0 +1 @@
/* Add your CSS here */

View file

@ -0,0 +1 @@
// Add your JavaScript here

View file

@ -0,0 +1,8 @@
<?php
use Livewire\Livewire;
it('renders successfully', function () {
Livewire::test('[component-name]')
->assertStatus(200);
});

Some files were not shown because too many files have changed in this diff Show more