### Get Configuration Value Examples Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/config.md Demonstrates retrieving configuration values using the getValue method. Examples cover default, website, and store scopes. Ensure the Config class is available, typically via dependency injection. ```php $config = app(Config::class); // Get default scope value $apiKey = $config->getValue('magewire/api/key'); // Get website-specific value $websiteConfig = $config->getValue( 'magewire/api/key', ScopeInterface::SCOPE_WEBSITE, 'base' // website code ); // Get store-specific value $storeConfig = $config->getValue( 'magewire/api/key', ScopeInterface::SCOPE_STORE, 'default' // store code ); ``` -------------------------------- ### Simple Page Redirect Example Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/redirects-and-navigation.md Shows a basic example of redirecting to a static URL from a component method. ```php class ProductComponent extends Component { public function gotoCheckout() { $this->redirect('/checkout'); } } ``` -------------------------------- ### Update Dependencies and Magento Setup Source: https://github.com/magewirephp/magewire/blob/main/UPGRADING.md Run composer update for Magewire and its dependencies, followed by Magento setup and cache commands. ```bash composer update magewirephp/magewire --with-all-dependencies bin/magento setup:upgrade bin/magento setup:di:compile bin/magento cache:flush ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/magewirephp/magewire/blob/main/CONTRIBUTING.md Clone the Magewire repository and install project dependencies using Composer and npm. Composer install also sets up pre-commit and commit-msg hooks. ```bash git clone https://github.com/magewirephp/magewire.git cd magewire composer install npm install ``` -------------------------------- ### PublicPropertyNotFoundException Example Scenario Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/errors.md Shows examples of valid and invalid property assignments on a Magewire component, highlighting when PublicPropertyNotFoundException is thrown for non-existent or non-public properties. ```php class MyComponent extends Component { public $email = ''; private $secret = 'hidden'; } $component = new MyComponent(); // Valid $component->email = 'user@example.com'; // Throws PublicPropertyNotFoundException - property doesn't exist $component->phone = '555-1234'; // Throws PublicPropertyNotFoundException - property is not public $component->secret = 'exposed'; ``` -------------------------------- ### Config Class Constructor Example Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/config.md This example shows how the Config class is typically injected via dependency injection in Magento. No explicit instantiation is usually needed in service classes. ```php class MyService { public function __construct( private readonly Config $config ) {} } ``` -------------------------------- ### Install Playwright Dev-Dependencies Source: https://github.com/magewirephp/magewire/blob/main/tests/Playwright/README.md Install all necessary development dependencies for Playwright using npm. Ensure you are in the Playwright tests directory. ```sh npm install ``` -------------------------------- ### Complete Event Flow Example Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/eventbus.md Demonstrates registering 'before', 'standard', and 'after' listeners for an event, and then triggering the event with middleware processing. ```php class MyComponent extends Component { protected function mount() { $bus = app(EventBus::class); // Register a before listener $bus->before('value:change', function($component) { return function($value) { // Pre-process: convert to uppercase return strtoupper($value); }; }); // Register standard listeners $bus->on('value:change', function($component, $value) { logger()->info("Value changing to: $value"); }); // Register an after listener $bus->after('value:change', function($component) { return function($value) { // Post-process: log length logger()->debug("Final value length: " . strlen($value)); return $value; }; }); } public function updateValue($newValue) { // Trigger the event $finisher = trigger('value:change', $this, $newValue); // Apply all middleware $processedValue = $finisher($newValue); // Use the processed value $this->value = $processedValue; } } ``` -------------------------------- ### Install Magewire via Composer Path Repository Source: https://github.com/magewirephp/magewire/blob/main/CONTRIBUTING.md Use this configuration in your composer.json to install Magewire from a local path during development. This allows for direct testing of local changes. ```json { "repositories": [ { "type": "path", "url": "/path/to/magewire" } ], "require": { "magewirephp/magewire": "*" } } ``` -------------------------------- ### store($instance) Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/helper-functions.md Get or create a store for component state across requests. This allows you to manage and persist state for components. ```APIDOC ## store($instance) ### Description Get or create a store for component state across requests. ### Parameters #### Path Parameters - **$instance** (object|null) - Optional - Component or object to store state for ### Returns `Store` — State store instance. ### Example ```php // Store component state store($component)->set('isLoading', true); $isLoading = store($component)->get('isLoading'); // Check if value exists if (store($component)->has('errorMessage')) { echo store($component)->get('errorMessage'); } // Remove from store store($component)->forget('temporaryData'); ``` ``` -------------------------------- ### Example Redirects with Navigate Option Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/redirects-and-navigation.md Demonstrates using the `redirect` method for both standard server redirects and JavaScript-driven navigation by setting the `navigate` parameter to true. ```php class CheckoutComponent extends Component { public function goToCart() { $this->redirect('/checkout/cart'); } public function confirmOrder() { $this->redirect('/order-confirmation', navigate: true); } } ``` -------------------------------- ### Environment-Specific Settings Example Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/configuration.md Define environment-specific configurations for Magewire by using separate .env files for different environments like staging and production. ```bash # staging/.env MAGEWIRE_DEBUG=1 MAGEWIRE_API_ENDPOINT=https://staging-api.example.com # production/.env MAGEWIRE_DEBUG=0 MAGEWIRE_API_ENDPOINT=https://api.example.com ``` -------------------------------- ### Form Component Example: Automatic Validator Injection Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/component-form.md Example demonstrating how the validator is automatically injected into a Form component subclass. No explicit instantiation is needed. ```php class ProductForm extends Form { // The validator is automatically injected } ``` -------------------------------- ### Catching PublicPropertyNotFoundException Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/errors.md Provides a code example for catching and handling PublicPropertyNotFoundException during property assignment attempts, logging the specific error. ```php use Magewirephp\Magewire\Exceptions\PublicPropertyNotFoundException; try { $component->undefinedProp = 'value'; } catch (PublicPropertyNotFoundException $e) { logger()->error('Property assignment failed: ' . $e->getMessage()); } ``` -------------------------------- ### Accessing and Using EventBus Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/eventbus.md Demonstrates how to get an instance of the EventBus and use global helper functions to trigger and listen to events. Ensure the EventBus class is imported or available in your scope. ```php use WireUi ants oundation\EventBus; // In a component or anywhere: $bus = app(EventBus::class); // Or use the global helper: trigger('event:name', $arg1, $arg2); on('event:name', function(...) { }); before('event:name', function(...) { }); after('event:name', function(...) { }); off('event:name', $callback); ``` -------------------------------- ### Reading Magewire Configuration in a Component Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/config.md Access Magewire-specific configuration values within a component. This example shows how to get 'items_per_page', 'api_endpoint', and a feature flag, providing default values if the configuration is not set. ```php class ProductListComponent extends Component { public $itemsPerPage = 20; protected function mount() { $config = app(Config::class); // Get items per page from admin config $this->itemsPerPage = $config->getValue( 'magewire/catalog/items_per_page' ) ?? 20; // Get API endpoint from environment $apiEndpoint = $config->getValue('magewire/api/endpoint'); // Get feature flag $enableSearch = $config->getValue( 'magewire/features/enable_search' ) ?? false; } public function search($query) { // Use configured values $results = apiCall( config('magewire/api/endpoint'), 'search', ['q' => $query, 'limit' => $this->itemsPerPage] ); } } ``` -------------------------------- ### Example Usage of HandlesRedirects Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/types.md Illustrates how to use the `redirect` method from the HandlesRedirects trait to navigate the user to a different URL. It shows both a standard redirect and a redirect with client-side navigation enabled. ```php public function goToCheckout() { $this->redirect('/checkout'); // Or with navigation $this->redirect('/checkout', navigate: true); } ``` -------------------------------- ### MethodNotFoundException Example Scenario Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/errors.md Illustrates valid and invalid method calls on a Magewire component, demonstrating when MethodNotFoundException is thrown for non-existent or non-public methods. ```php class MyComponent extends Component { public function save() { // ... } private function internalMethod() { // ... } } $component = new MyComponent(); $component->save(); // OK $component->internalMethod(); // Throws MethodNotFoundException (private method) $component->nonExistent(); // Throws MethodNotFoundException (doesn't exist) ``` -------------------------------- ### Navigate to Playwright Tests Directory Source: https://github.com/magewirephp/magewire/blob/main/tests/Playwright/README.md Change the current directory to the Playwright tests folder. This is the first step before installing dependencies. ```sh cd tests/Playwright ``` -------------------------------- ### RequestMode Enum Usage Example Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/types.md Demonstrates how to use the RequestMode enum to check if the current request is a subsequent one. ```php $mode = RequestMode::SUBSEQUENT; if ($mode->isSubsequent()) { // Handle subsequent request } ``` -------------------------------- ### Example: 'url' Validation Rule Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/validation.md Use the 'url' rule to validate that a field contains a valid URL format. ```php 'site' => 'url' ``` -------------------------------- ### Example: 'confirmed' Validation Rule Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/validation.md Use the 'confirmed' rule to ensure a field matches its corresponding 'field_confirmation' field. ```php 'password' => 'confirmed' ``` -------------------------------- ### Example: 'min:N' Validation Rule Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/validation.md Use the 'min:N' rule to enforce a minimum length or value for a field. ```php 'name' => 'min:2' ``` -------------------------------- ### FlashMessageType Enum Usage Example Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/types.md Shows how to set a flash message type using the FlashMessageType enum. Ensure the FlashMessage class is imported. ```php use Magewirephp\Magewire\Features\SupportMagentoFlashMessages\FlashMessageType; $message = new FlashMessage(__('Item saved!')); $message->as(FlashMessageType::Success); ``` -------------------------------- ### Example Usage of InteractsWithProperties Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/types.md Demonstrates how to use the property management methods provided by the InteractsWithProperties trait within a Magewire component. This includes resetting specific properties, retrieving all properties, filtering properties, and filling properties from external data. ```php class ProductComponent extends Component { public $name = ''; public $price = 0; public $quantity = 1; public function reset() { // Reset all properties to initial values parent::reset(); // Reset only specific properties $this->reset('quantity', 'price'); // Reset all except name $this->resetExcept('name'); } public function getProduct() { $all = $this->all(); // ['name' => '', 'price' => 0, 'quantity' => 1] $prices = $this->only(['price', 'quantity']); $withoutQuantity = $this->except('quantity'); } public function updateFromApi($data) { $this->fill($data); // Syncs public properties } } ``` -------------------------------- ### Get Specific Properties with only(...$properties) Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/properties-and-state.md Use `only` to retrieve a subset of properties, either by passing an array of property names or as variable arguments. ```php public function only($properties): array ``` ```php // Using array $form = $this->only(['name', 'email', 'phone']); // Using arguments $contactInfo = $this->only('name', 'email'); ``` -------------------------------- ### Get All Properties with all() Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/properties-and-state.md Retrieve all public properties of the component as an associative array using the `all()` method. This is useful for auditing or bulk operations. ```php public function all(): array ``` ```php $allProps = $this->all(); // Returns: ['name' => '', 'email' => '', ...] // Use for bulk operations database()->insert('audit_log', [ 'component' => $this->getName(), 'state' => json_encode($this->all()) ]); ``` -------------------------------- ### Using the Global Config Helper Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/config.md The `config()` helper function offers a convenient way to read configuration values. You can also provide a default value as the second argument. ```php // Global helper function (recommended) $apiKey = config('magewire.api.key'); $debugMode = config('magewire.debug', false); // with default ``` ```php // More verbose form $config = app(Config::class); $apiKey = $config->getValue('magewire/api/key'); ``` -------------------------------- ### Redirect with Route Parameters Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/redirects-and-navigation.md Illustrates how to construct a URL with dynamic route parameters for redirection. ```php class OrderComponent extends Component { public $orderId = null; public function viewOrder($id) { $this->redirect("/orders/{$id}/details"); } } ``` -------------------------------- ### Playwright End-to-End Testing Commands Source: https://github.com/magewirephp/magewire/blob/main/CONTRIBUTING.md Commands to set up and run Playwright end-to-end tests for Magewire. This includes installing dependencies, running tests headlessly, interactively, or targeting specific files. ```bash cd tests/Playwright cp .env.example .env # configure BASE_URL + credentials npm install && npx playwright install npx playwright test # headless npx playwright test --ui # interactive npx playwright test tests/example.spec.ts # single file ``` -------------------------------- ### Form Component Example: Rules as Property Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/component-form.md Example of defining validation rules for a ContactForm component using the $rules property. Rules are specified as an associative array. ```php class ContactForm extends Form { protected $rules = [ 'name' => 'required|min:2', 'email' => 'required|email', 'message' => 'required|min:10' ]; } ``` -------------------------------- ### Form Submission with Redirect Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/redirects-and-navigation.md Example of a contact form that validates input, saves a message, shows a success flash message, and then redirects to a thank-you page upon successful submission. Includes error handling for validation failures. ```php class ContactFormComponent extends Component { public $name = ''; public $email = ''; public $message = ''; protected $rules = [ 'name' => 'required|min:2', 'email' => 'required|email', 'message' => 'required|min:10' ]; public function submit() { try { // Validate $this->validate(); // Save message $contact = contactFactory()->create([ 'name' => $this->name, 'email' => $this->email, 'message' => $this->message, 'created_at' => now() ]); $contact->save(); // Show success and redirect $this->magewireFlashMessages() ->success(__('Thank you! We\'ll be in touch soon.')); $this->redirect('/thank-you'); } catch (AcceptableException $e) { // Show validation errors (component stays on same page) $this->magewireFlashMessages() ->error(__('Please correct the errors below')); } } } ``` -------------------------------- ### Form Component Example: Custom Error Messages Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/component-form.md Example of overriding default validation error messages for a ContactForm component using the $messages property. Messages are mapped to specific rules. ```php class ContactForm extends Form { protected $messages = [ 'name.required' => 'Please enter your name', 'email.email' => 'Please enter a valid email address' ]; } ``` -------------------------------- ### Type Casting Configuration Values Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/config.md Demonstrates how to retrieve and cast configuration values to their appropriate types. Remember to handle type casting explicitly as values are returned as strings. ```php $config = app(Config::class); // Returns string "1" or "0", cast to bool $debug = (bool) $config->getValue('magewire/debug_mode'); // Returns comma-separated string, split it $allowedMethods = explode(',', $config->getValue('magewire/allowed_methods')); // Returns JSON, decode it $settings = json_decode($config->getValue('magewire/settings'), true); ``` -------------------------------- ### Get Component Name Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/component.md Returns the registered name of the Magewire component. ```php public function getName() ``` -------------------------------- ### Get Component ID Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/component.md Retrieves the currently assigned unique identifier for the component. ```php function getId() ``` -------------------------------- ### Create a Basic Magewire Component Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/00-START-HERE.txt Define a new component by extending the base Component class. Include public properties for state and methods for actions. ```php class MyComponent extends Component { public $property = ''; public function method() { } } ``` -------------------------------- ### Get Magewire Alias Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/component.md Retrieves the custom alias assigned to the component, if one has been set. ```php public function getMagewireAlias(): string|null ``` -------------------------------- ### Example: 'required' Validation Rule Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/validation.md Use the 'required' rule to ensure a field must have a value. ```php 'email' => 'required' ``` -------------------------------- ### Create Fluent String Instance or Access Str Utilities Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/helper-functions.md Use the `str()` helper to create a fluent string instance for methods like `slug()`, or to access static utility methods like `camel()`. ```php function str($string = null) { if ($string === null) { return new Str(); } return new class($string) implements Stringable { private $string; public function __construct($string) { $this->string = (string) $string; } public function __toString(): string { return $this->string; } public function slug(string $separator = '-'): string { return str_replace(' ', $separator, ucwords($this->string)); } // Add other Stringable methods as needed }; } ``` ```php // Create fluent string instance $slug = str('Hello World')->slug(); // "hello-world" // Access Str utilities $camelCase = str()->camel('hello_world'); // "helloWorld" ``` -------------------------------- ### Example: 'integer' Validation Rule Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/validation.md Use the 'integer' rule to validate that a field contains only an integer value. ```php 'count' => 'integer' ``` -------------------------------- ### Instantiate FlashMessage Class Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/flash-messages.md Create a new FlashMessage instance with initial content. This is the basic constructor for the FlashMessage object. ```php use Magewirephp\Magewire\Features\SupportMagentoFlashMessages\FlashMessage; $msg = new FlashMessage(__('Hello World')); $msg->asSuccess(); ``` -------------------------------- ### Example: 'numeric' Validation Rule Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/validation.md Use the 'numeric' rule to validate that a field contains only numeric characters. ```php 'age' => 'numeric' ``` -------------------------------- ### Simple Page Redirect Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/redirects-and-navigation.md Demonstrates a basic redirect to a static URL. ```APIDOC ### Simple Page Redirect ```php class ProductComponent extends Component { public function gotoCheckout() { $this->redirect('/checkout'); } } ``` ``` -------------------------------- ### Retrieving All Validation Errors Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/component-form.md Call this method to get a MessageBag containing all validation errors associated with the component. ```php getErrorBag(); // Returns MessageBag with all errors ``` -------------------------------- ### Example: 'date' Validation Rule Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/validation.md Use the 'date' rule to validate that a field contains a valid date format. ```php 'dob' => 'date' ``` -------------------------------- ### before($name, $callback) Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/helper-functions.md Registers a 'before' listener that executes prior to the standard listeners for a given event. ```APIDOC ## before($name, $callback) ### Description Register a "before" listener that executes before standard listeners. ### Parameters #### Path Parameters - **$name** (string) - Required - Event name - **$callback** (callable) - Required - Listener function ### Request Example ```php before('validation', function($data) { // Execute before standard validation return function($value) { return sanitize($value); }; }); ``` ### Response #### Success Response (200) - **callable** - Function to unregister listener. ``` -------------------------------- ### tap($callback) Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/component.md Executes a callback on the component and returns the component instance for fluent API usage. ```APIDOC ## tap($callback) ### Description Executes a callback on the component and returns the component instance (fluent API). ### Method ```php public function tap($callback): static ``` ### Parameters #### Path Parameters - **$callback** (callable) - Required - Function receiving the component as argument ### Returns `static` — The component instance for method chaining. ### Example ```php $component->tap(function ($component) { $component->setName('my-component'); $component->resetProperties(); }); ``` ``` -------------------------------- ### Configuration Class Reference Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/INDEX.md Reference to the Magewire configuration class. ```php Magewirephp/Magewire/Config lib/Magewire/Config.php ``` -------------------------------- ### High-Performance Configuration Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/configuration.md Optimize Magewire performance by enabling caching and streaming, and adjusting debounce and delay settings via environment variables. ```bash # .env MAGEWIRE_CACHE_COMPONENTS=1 MAGEWIRE_CACHE_COMPILED_VIEWS=1 MAGEWIRE_STREAMING_ENABLED=1 MAGEWIRE_VALIDATION_DEBOUNCE=750 MAGEWIRE_LOADER_DELAY=300 ``` -------------------------------- ### PropertyNotFoundException Example Scenario Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/errors.md Illustrates a scenario where accessing a non-existent public property on a Magewire component triggers a PropertyNotFoundException. ```php class MyComponent extends Component { public $name = ''; } $component = new MyComponent(); $value = $component->nonExistentProperty; // Throws PropertyNotFoundException ``` -------------------------------- ### Get Component ID Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/component.md Retrieve the unique identifier for the current component instance. Useful for debugging or referencing the component. ```php function id() { // ... } ``` ```php class MyComponent extends Component { public function mount() { $componentId = $this->id(); // "abc123def456" } } ``` -------------------------------- ### Redirect with Query Parameters Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/redirects-and-navigation.md Demonstrates redirecting to a URL that includes URL-encoded query parameters. ```php class SearchComponent extends Component { public $query = ''; public function submitSearch() { $this->redirect('/search?q=' . urlencode($this->query)); } } ``` -------------------------------- ### Example: 'regex:pattern' Validation Rule Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/validation.md Use the 'regex:pattern' rule to validate a field against a regular expression pattern. ```php 'code' => 'regex:/^[A-Z0-9]+$/' ``` -------------------------------- ### Login Flow with Client-Side Redirect Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/redirects-and-navigation.md Demonstrates a login component that authenticates a user, sets session data, optionally sets a remember-me cookie, and then performs a client-side redirect to the customer dashboard upon successful login. Includes error handling for authentication failures. ```php class LoginComponent extends Component { public $email = ''; public $password = ''; public $rememberMe = false; public function login() { try { // Authenticate $user = authService()->authenticate($this->email, $this->password); if (!$user) { $this->magewireFlashMessages() ->error(__('Invalid email or password')); return; } // Login user session()->setUser($user); if ($this->rememberMe) { // Set remember-me cookie setcookie('auth_token', generateToken(), time() + 30*24*60*60); } // Redirect to dashboard $this->redirect('/customer/dashboard', navigate: true); } catch (Exception $e) { logger()->error('Login error: ' . $e->getMessage()); $this->magewireFlashMessages() ->error(__('An error occurred during login')); } } } ``` -------------------------------- ### Example: 'max:N' Validation Rule Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/validation.md Use the 'max:N' rule to enforce a maximum length or value for a field. ```php 'name' => 'max:100' ``` -------------------------------- ### Example: 'email' Validation Rule Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/validation.md Use the 'email' rule to validate that a field contains a valid email address format. ```php 'email' => 'email' ``` -------------------------------- ### Redirect with Route Parameters Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/redirects-and-navigation.md Shows how to redirect to a URL that includes dynamic route parameters. ```APIDOC ### With Route Parameters ```php class OrderComponent extends Component { public $orderId = null; public function viewOrder($id) { $this->redirect("/orders/{$id}/details"); } } ``` ``` -------------------------------- ### Catching PropertyNotFoundException Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/errors.md Demonstrates how to catch and handle a PropertyNotFoundException using a try-catch block, logging the error message. ```php use Magewirephp\Magewire\Exceptions\PropertyNotFoundException; try { $value = $component->unknownProp; } catch (PropertyNotFoundException $e) { logger()->error($e->getMessage()); } ``` -------------------------------- ### Event System Class Reference Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/INDEX.md Reference to the Magewire event bus class. ```php Magewirephp/Magewire/EventBus dist/EventBus.php ``` -------------------------------- ### Retrieve Flash Message Type Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/flash-messages.md Use the `type` method to get the `FlashMessageType` enum value associated with the flash message. ```php public function type(): FlashMessageType ``` -------------------------------- ### config($key, $default) Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/helper-functions.md Retrieve configuration values from Magento config or .env file. Supports dot notation for nested keys. ```APIDOC ## config($key, $default) ### Description Retrieve configuration values from Magento config or .env file. ### Parameters #### Path Parameters - **$key** (string) - Required - Config key path (dot notation) - **$default** (mixed) - Optional - Default value if key not found ### Returns `mixed` — Configuration value. ### Example ```php $apiKey = config('magewire.api_key', 'default-key'); $isDebug = config('magewire.debug_mode', false); // Config can come from: // 1. config.xml (path attributes) // 2. .env file (MAGEWIRE_API_KEY) // 3. env.php (deployment config) ``` ``` -------------------------------- ### Generate Portman Output Source: https://github.com/magewirephp/magewire/blob/main/CONTRIBUTING.md Build the `dist/` directory by running `vendor/bin/portman build`. This command generates Portman output from the `lib/Livewire/` and `portman/Livewire/` directories. ```bash vendor/bin/portman build ``` -------------------------------- ### Retrieve Flash Message Phrase Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/flash-messages.md Use the `message` method to get the `Phrase` object representing the flash message content. ```php public function message(): Phrase ``` -------------------------------- ### Access Configuration Values Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/00-START-HERE.txt Retrieve configuration settings using the config() helper function, providing the configuration key. ```php config('magewire.key'); // Get config value ``` -------------------------------- ### Helper Methods for Property Access Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/properties-and-state.md Utilize helper methods from the `InteractsWithProperties` trait to get, check, or filter component properties. ```php class MyComponent extends Component { public $name = ''; public $email = ''; public function showAll() { // Get all properties $all = $this->all(); // Returns: ['name' => '', 'email' => ''] // Get specific properties $nameOnly = $this->only(['name']); // Get all except specific $withoutEmail = $this->except(['email']); // Check if property exists if ($this->hasProperty('name')) { // ... } } } ``` -------------------------------- ### app($abstract, $arguments) Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/helper-functions.md Retrieve services from the Magento service container (ObjectManager). Allows access to Magento's dependency injection. ```APIDOC ## app($abstract, $arguments) ### Description Retrieve services from the Magento service container (ObjectManager). ### Parameters #### Path Parameters - **$abstract** (string|null) - Optional - Service class/interface to resolve - **$arguments** (array) - Optional - Constructor arguments ### Returns `mixed` — Resolved service instance or container. ### Example ```php // Get a service from the container $logger = app('Psr\Log\LoggerInterface'); // Get ObjectManager directly $om = app(); $factory = $om->create('Some\Factory\Class'); ``` ``` -------------------------------- ### Get Property Value Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/component.md Retrieves a property value using the reactive property system. Throws a PropertyNotFoundException if the property does not exist. ```php public function __get($property) ``` ```php $email = $component->email; // Triggers reactive property access ``` -------------------------------- ### Development Environment Configuration Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/configuration.md Configure Magewire for development environments using environment variables in the .env file. ```bash # .env MAGEWIRE_DEBUG=1 MAGEWIRE_VALIDATION_MODE=realtime MAGEWIRE_LOADER_ENABLED=1 ``` -------------------------------- ### Production Environment Configuration Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/configuration.md Set production-specific Magewire configurations using environment variables in the .env file. ```bash # .env MAGEWIRE_DEBUG=0 MAGEWIRE_API_KEY=sk_live_production_key MAGEWIRE_VALIDATION_DEBOUNCE=1000 MAGEWIRE_ALLOWED_METHODS=save,update,search ``` -------------------------------- ### Modal Component for Confirmation Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/README.md Implement a modal component to display messages and handle confirmation actions. Use `open` to show the modal and `confirm` to trigger a callback. ```php class ConfirmModalComponent extends Component { public $isOpen = false; public $message = ''; public $onConfirm = null; public function open($message) { $this->message = $message; $this->isOpen = true; } public function confirm() { if ($this->onConfirm) { call_user_func($this->onConfirm); } $this->close(); } public function close() { $this->isOpen = false; } } ``` -------------------------------- ### Example: 'unique:table' Validation Rule Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/validation.md Use the 'unique:table' rule to ensure a value is unique within a specified database table. ```php 'sku' => 'unique:products' ``` -------------------------------- ### Registering a 'Before' Listener Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/eventbus.md Register a 'before' listener that executes prior to standard listeners, allowing for data pre-processing. ```APIDOC ## before($name, $callback) ### Description Register a "before" listener that executes before standard listeners and can pre-process data. ### Method `before` ### Parameters #### Path Parameters - **$name** (string) - Required - Event name - **$callback** (callable) - Required - Listener function (may return middleware) ### Request Example ```php $eventBus->before('validation', function($data) { // Pre-process data before validation return function($value) { return trim($value); // Trim whitespace }; }); ``` ### Response #### Success Response - **callable** - Function to unregister listener. ``` -------------------------------- ### Retrieve Configuration Values Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/helper-functions.md Fetches configuration values from Magento's config, .env file, or env.php. Provides a fallback to a default value if the configuration key is not found. ```php function config(string $key, mixed $default = null): mixed ``` ```php $apiKey = config('magewire.api_key', 'default-key'); $isDebug = config('magewire.debug_mode', false); // Config can come from: // 1. config.xml (path attributes) // 2. .env file (MAGEWIRE_API_KEY) // 3. env.php (deployment config) ``` -------------------------------- ### Reading Configuration Values with Scope Constants Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/config.md Use these constants with `getValue()` to retrieve configuration values from specific scopes: default, website, or store. Provide the website or store code when retrieving values for those scopes. ```php use Magento\Framework\App\Config\ScopeConfigInterface; use Magento\Store\Model\ScopeInterface; // Retrieve default scope value $value = $config->getValue('path', ScopeConfigInterface::SCOPE_TYPE_DEFAULT); ``` ```php // Retrieve website scope value $value = $config->getValue('path', ScopeInterface::SCOPE_WEBSITE, 'website_code'); ``` ```php // Retrieve store scope value $value = $config->getValue('path', ScopeInterface::SCOPE_STORE, 'store_code'); ``` -------------------------------- ### Redirect with Query Parameters Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/redirects-and-navigation.md Illustrates redirecting to a URL with query parameters, useful for search or filtering. ```APIDOC ### With Query Parameters ```php class SearchComponent extends Component { public $query = ''; public function submitSearch() { $this->redirect('/search?q=' . urlencode($this->query)); } } ``` ``` -------------------------------- ### Access Magento Service Container Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/helper-functions.md Retrieves services from the Magento service container (ObjectManager). Can be used to get specific services or the ObjectManager instance itself. ```php function app($abstract = null, array $arguments = []): mixed ``` ```php // Get a service from the container $logger = app('Psr\Log\LoggerInterface'); // Get ObjectManager directly $om = app(); $factory = $om->create('Some\Factory\Class'); ``` -------------------------------- ### Run Code Linters and Formatters Source: https://github.com/magewirephp/magewire/blob/main/CONTRIBUTING.md Execute these commands before submitting a pull request to ensure code adheres to project standards. This includes linting, formatting, and building generated files. ```bash mago lint mago format vendor/bin/portman build vendor/bin/php-cs-fixer fix dist/ ``` -------------------------------- ### Trigger Event and Get Finisher Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/eventbus.md Trigger an event and receive a finisher function. This function can then be used to process data through all registered middleware (before, standard, after). ```php // Trigger event and get finisher $finisher = $eventBus->trigger('process:value', $component); // Use finisher to process data through all middleware $processed = $finisher($myValue); // Or use with extras $result = $finisher($myValue, $extra1, $extra2); ``` -------------------------------- ### Access Config with config() Helper in Component Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/configuration.md Use the global `config()` helper function within your component to access configuration values. A default value can be provided. ```php class MyComponent extends Component { public function mount() { $apiKey = config('magewire.api.key'); $debugMode = config('magewire.debug.enabled', false); // with default } } ``` -------------------------------- ### Example: 'before:date' Validation Rule Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/validation.md Use the 'before:date' rule to validate that a field's date is before a specified date or another field. ```php 'start' => 'before:end' ``` -------------------------------- ### getValue Method Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/config.md Retrieves a configuration value from system config or environment config, respecting a defined resolution order. ```APIDOC ## getValue $path, $scope, $scopeCode ### Description Retrieves a configuration value from system config or environment config. The method checks path mappings, Magento system config, and then environment config. ### Parameters #### Path Parameters - **$path** (string) - Required - Configuration path (dot notation) - **$scope** (string) - Optional - Config scope (default, website, store). Defaults to `ScopeConfigInterface::SCOPE_TYPE_DEFAULT`. - **$scopeCode** (string|null) - Optional - Scope code (website/store ID). Defaults to null. ### Returns `array|mixed|string|null` - Configuration value or null if not found. ### Throws - `Magento\Framework\Exception\FileSystemException` - `Magento\Framework\Exception\RuntimeException` ### Example ```php $config = app(Config::class); // Get default scope value $apiKey = $config->getValue('magewire/api/key'); // Get website-specific value $websiteConfig = $config->getValue( 'magewire/api/key', ScopeInterface::SCOPE_WEBSITE, 'base' // website code ); // Get store-specific value $storeConfig = $config->getValue( 'magewire/api/key', ScopeInterface::SCOPE_STORE, 'default' // store code ); ``` ``` -------------------------------- ### Example: 'after:date' Validation Rule Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/validation.md Use the 'after:date' rule to validate that a field's date is after a specified date or another field. ```php 'end' => 'after:start' ``` -------------------------------- ### Declare Public Properties for Synchronization Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/errors.md Ensure component properties intended for synchronization are declared as public. This example shows how to declare and update a public property. ```php class MyComponent extends Component { public $email = ''; // Must be public and declared public function updateEmail($newEmail) { $this->email = $newEmail; // Now works } } ``` -------------------------------- ### Set Magewire Configuration Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/README.md Configure Magewire settings using environment variables. Ensure keys are set for API access and debugging. ```bash # .env MAGEWIRE_DEBUG=1 MAGEWIRE_API_KEY=your-key MAGEWIRE_VALIDATION_DEBOUNCE=750 ``` -------------------------------- ### Execute Callback and Return Component Instance Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/component.md The tap method allows you to execute a callback function on the component instance and then return the component instance itself, enabling fluent API usage for chaining methods. ```php public function tap($callback): static ``` ```php $component->tap(function ($component) { $component->setName('my-component'); $component->resetProperties(); }); ``` -------------------------------- ### Conventional Commit Message Examples Source: https://github.com/magewirephp/magewire/blob/main/CONTRIBUTING.md Follow the Conventional Commits specification for commit messages. This format helps in automating changelog generation and version bumping. ```git feat(compiler): add @render.parent directive fix(snapshot): handle null property reassignment chore(portman): bump Livewire to 3.7.12 ``` -------------------------------- ### Display Flash Messages in Frontend Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/flash-messages.md Example of how to conditionally display flash messages in your Blade template. Ensure your view includes the `magewire-messages` component for automatic rendering. ```html
@if($magewire->hasMagewireFlashMessages()) @foreach($magewire->getMagewireFlashMessages() as $message)
{{ $message->message() }}
@endforeach @endif
``` -------------------------------- ### Create a pipe for sequential data transformations Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/helper-functions.md Use `pipe` to establish a pipeline for applying a series of data transformations sequentially, such as filtering, mapping, and sorting. ```php $result = pipe($data) ->through('filter') ->through('map') ->through('sort') ->get(); ``` -------------------------------- ### Example: 'required_if:field,value' Validation Rule Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/validation.md Use the 'required_if:field,value' rule to make a field required only if another field has a specific value. ```php 'note' => 'required_if:type,other' ``` -------------------------------- ### Wrap a component for fluent operations Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/helper-functions.md Use `wrap` to create a fluent wrapper around a component, enabling chainable operations like `tap` and `commit`. ```php wrap($component)->tap(function($comp) { $comp->setName('my-component'); $comp->resetProperties(); })->commit(); ``` -------------------------------- ### Example: 'in:val1,val2' Validation Rule Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/validation.md Use the 'in:val1,val2' rule to validate that a field's value is one of the specified values. ```php 'status' => 'in:draft,published' ``` -------------------------------- ### Skip Component Mount Hook Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/component.md Prevent the `mount` lifecycle hook from executing for this component instance. Useful for components that should not perform initial setup under certain conditions. ```php public function skipMount(): void ``` ```php public function beforeCreate() { if ($this->isAlreadyInitialized()) { $this->skipMount(); } } ``` -------------------------------- ### Environment Variables (.env) for Magewire Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/config.md Sets configuration values using environment variables. Prefixes like `MAGEWIRE_` are used to namespace settings. ```bash # .env file MAGEWIRE_API_KEY=your-secret-key MAGEWIRE_DEBUG_MODE=1 ``` -------------------------------- ### InteractsWithProperties Trait Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/types.md Manages property interactions and synchronization within Magewire components. Provides methods to check, get, fill, reset, and manipulate component properties. ```APIDOC ## InteractsWithProperties Trait ### Description Manages property interactions and synchronization within Magewire components. Provides methods to check, get, fill, reset, and manipulate component properties. ### Methods - `hasProperty(string $prop): bool` Check if property exists. - `getPropertyValue(string $name)` Get property value (supports dots). - `fill(array|DataObject $values): void` Fill properties from array/object. - `reset(...$properties): void` Reset properties to initial state. - `resetExcept(...$properties): void` Reset all except specified properties. - `pull($properties = null)` Get and reset properties. - `only(array $properties): array` Get only specified properties. - `except(array $properties): array` Get all except specified properties. - `all(): array` Get all public properties. ### Example ```php class ProductComponent extends Component { public $name = ''; public $price = 0; public $quantity = 1; public function reset() { // Reset all properties to initial values parent::reset(); // Reset only specific properties $this->reset('quantity', 'price'); // Reset all except name $this->resetExcept('name'); } public function getProduct() { $all = $this->all(); // ['name' => '', 'price' => 0, 'quantity' => 1] $prices = $this->only(['price', 'quantity']); $withoutQuantity = $this->except('quantity'); } public function updateFromApi($data) { $this->fill($data); // Syncs public properties } } ``` ``` -------------------------------- ### Temporary State Storage with `store()` Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/properties-and-state.md Use the `store()` helper to temporarily store component state that needs to persist across requests within the same component instance. This is useful for maintaining context between actions, like remembering a previous step in a multi-step process. ```php use function Magewirephp\Magewire\store; class CheckoutComponent extends Component { public function beforeUpdate() { // Store state temporarily store($this)->set('previousStep', $this->currentStep); } public function goBack() { // Retrieve stored state $this->currentStep = store($this)->get('previousStep'); } } ``` -------------------------------- ### Register a 'before' event listener Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/helper-functions.md Use `before` to register a listener that executes prior to the standard listeners for a given event. It can return a closure to modify the event's processing. ```php before('validation', function($data) { // Execute before standard validation return function($value) { return sanitize($value); }; }); ``` -------------------------------- ### Get All Validation Errors Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/validation.md Retrieve the entire error bag, which is an instance of `Illuminate\Support\MessageBag`. This is useful for inspecting all current validation errors, checking for specific fields, or iterating through them. ```php try { $this->validate(); } catch (AcceptableException $e) { $errors = $this->getErrorBag(); // Check if field has error if ($errors->has('email')) { $messages = $errors->get('email'); } // Get all errors foreach ($errors->toArray() as $field => $messages) { foreach ($messages as $message) { logger()->error("$field: $message"); } } } ``` -------------------------------- ### Example: 'gt:field' Validation Rule Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/validation.md Use the 'gt:field' rule to validate that a field's value is strictly greater than another field's value. ```php 'max' => 'gt:min' ``` -------------------------------- ### Deployment Configuration (env.php) for Magewire Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/config.md Defines configuration values directly in the application's deployment configuration file. This method allows for environment-specific settings. ```php // app/etc/env.php return [ 'magewire' => [ 'api' => [ 'key' => 'your-secret-key' ] ] ]; ``` -------------------------------- ### Example: 'lt:field' Validation Rule Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/validation.md Use the 'lt:field' rule to validate that a field's value is strictly less than another field's value. ```php 'min' => 'lt:max' ``` -------------------------------- ### Access Configuration Values Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/README.md Retrieve configuration values using the global `config()` helper or by injecting and using the `Config` class from the application container. ```php $value = config('magewire.api.key'); ``` ```php $value = app(Config::class)->getValue('path'); ``` -------------------------------- ### Register Before Event Listener Source: https://github.com/magewirephp/magewire/blob/main/_autodocs/api-reference/eventbus.md Register a listener that executes before standard listeners. It can pre-process data and may return middleware. Use for data preparation before an event. ```php $eventBus->before('validation', function($data) { // Pre-process data before validation return function($value) { return trim($value); }; }); ```