### Installing Nette DI via Composer Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/di/readme.md This command demonstrates the recommended way to install the Nette DI library using Composer, the PHP dependency manager. It specifies that PHP versions 7.2 up to 8.3 are supported. ```Bash composer require nette/di ``` -------------------------------- ### Installing Nette Finder via Composer Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/finder/readme.md This command installs the Nette Finder library into your PHP project using Composer, the dependency manager for PHP. It adds the `nette/finder` package to your project's `composer.json` and downloads its dependencies, making the library available for use. ```shell composer require nette/finder ``` -------------------------------- ### Installing Nette Utils via Composer Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/utils/readme.md This command installs the Nette Utils library into your PHP project using Composer, the dependency manager for PHP. It adds the `nette/utils` package to your `composer.json` and downloads its dependencies, making the utility classes available for use in your application. ```Shell composer require nette/utils ``` -------------------------------- ### Installing Nette Bootstrap via Composer Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/bootstrap/readme.md This command installs the Nette Bootstrap library using Composer, the PHP dependency manager. It adds `nette/bootstrap` to your project's dependencies, making it available for use. This is the recommended method for integrating the library into a PHP project. ```Shell composer require nette/bootstrap ``` -------------------------------- ### Installing Nette RobotLoader via Composer Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/robot-loader/readme.md This command demonstrates how to install the Nette RobotLoader library using Composer, the dependency manager for PHP. It's the recommended and standard way to integrate the library into a PHP project. ```Shell composer require nette/robot-loader ``` -------------------------------- ### Installing Nette HTTP Component with Composer Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/http/readme.md This command installs the Nette HTTP component using Composer, the PHP dependency manager. It ensures all necessary files and dependencies are downloaded and configured for use in a PHP project. The component requires PHP 7.2 or higher. ```shell composer require nette/http ``` -------------------------------- ### Installing Tracy PHP Debugger via Composer Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/tracy/tracy/readme.md This command installs the Tracy PHP debugger library into your project using Composer, the dependency manager for PHP. It fetches the latest stable version of Tracy and adds it to your project's dependencies. ```Shell composer require tracy/tracy ``` -------------------------------- ### Installing Nette Component Model via Composer Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/component-model/readme.md This snippet demonstrates how to install the Nette Component Model library using Composer, the dependency manager for PHP. It requires PHP version 7.1 and supports up to 8.2, ensuring the necessary components are added to your project. ```Shell composer require nette/component-model ``` -------------------------------- ### Installing Nette Forms Client-side Support (JavaScript) Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/forms/readme.md This command installs the client-side JavaScript support for Nette Forms using npm, a package manager for JavaScript. This is necessary for enabling client-side validation features. ```bash npm install nette-forms ``` -------------------------------- ### Searching Files by Path Mask with Nette Finder in PHP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/finder/readme.md This PHP example demonstrates using a mask that includes directory patterns to find files. It searches for `*.jpg` files located within a subdirectory whose name starts with `imag`, using `*` as a wildcard for any characters except the directory separator (`/`). This allows for more specific path-based searches. ```php Finder::findFiles('imag*/*.jpg') ``` -------------------------------- ### Adding Comments in NEON Configuration Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/neon/readme.md This NEON example illustrates how to include comments. Lines starting with '#' are treated as full-line comments, and '#' can also be used for inline comments, with all characters to the right of '#' being ignored by the NEON interpreter. ```neon # this line will be ignored by the interpreter street: 742 Evergreen Terrace city: Springfield # this is ignored too country: USA ``` -------------------------------- ### Installing Nette Schema with Composer Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/schema/readme.md This snippet demonstrates how to install the Nette Schema library using Composer, the PHP dependency manager. It adds the `nette/schema` package to your project, making its classes available for use. ```shell composer require nette/schema ``` -------------------------------- ### Installing Nette NEON via Composer Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/neon/readme.md This command installs the Nette NEON library using Composer, the PHP dependency manager. It's the standard way to add NEON to a PHP project, requiring PHP version 7.1 or higher. ```Shell composer require nette/neon ``` -------------------------------- ### Installing Nette Forms via Composer (PHP) Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/forms/readme.md This command installs the Nette Forms library into your PHP project using Composer, the dependency manager for PHP. It requires PHP version 7.2 or higher and supports up to 8.1. ```bash composer require nette/forms ``` -------------------------------- ### Registering a Factory Interface in Nette NEON (Verbose Form) Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/di/readme.md This NEON snippet provides a more verbose way to register a factory interface using the `implement` key. This form allows for additional configuration options, such as `arguments` and `setup`, similar to regular service definitions. ```NEON services: barFactory: implement: IBarFactory ``` -------------------------------- ### Comprehensive NEON Configuration with Comments Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/neon/readme.md This NEON snippet provides a comprehensive example combining various features: unquoted keys/values, indentation-based structure, bulleted arrays, and both full-line and inline comments. It showcases a typical, readable NEON configuration file for a web application. ```neon # my web application config php: date.timezone: Europe/Prague zlib.output_compression: true # use gzip database: driver: mysql username: root password: beruska92 users: - Dave - Kryten - Rimmer ``` -------------------------------- ### Installing Nette PHP Generator with Composer Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/php-generator/readme.md This snippet demonstrates how to install the Nette PHP Generator library using Composer, the PHP dependency manager. Executing this command adds the library as a dependency to your project, making its classes and functions available for use. ```shell composer require nette/php-generator ``` -------------------------------- ### Registering Service with Setter Injection in Nette NEON Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/di/readme.md This NEON snippet shows how to configure a service to use setter injection. The `setup` section allows you to specify methods that should be called on the service instance after its creation, enabling dependencies to be passed via setters. ```NEON services: manager: factory: NewsletterManager setup: - setAnotherService ``` -------------------------------- ### Accessing GET Request Parameters in Nette HTTP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/http/readme.md This PHP code illustrates how to retrieve GET request parameters using the `getQuery()` method of the `Nette\Http\Request` object. It shows how to get all parameters as an array or a specific parameter by its key, returning `null` if the key is not found. ```php $all = $httpRequest->getQuery(); // array of all URL parameters $id = $httpRequest->getQuery('id'); // returns GET parameter 'id' (or null) ``` -------------------------------- ### Implementing Mailer with PHP's mail() function Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/di/readme.md This class provides a concrete implementation of the `Mailer` interface, utilizing PHP's built-in `mail()` function to send emails. It serves as a practical example of how the `Mailer` contract can be fulfilled. ```PHP class SendMailMailer implements Mailer { function send(Mail $mail, $to) { mail($to, $mail->subject, $mail->message); } } ``` -------------------------------- ### NEON Configuration Using Bulleted List for Arrays Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/neon/readme.md This NEON example demonstrates an alternative, more legible syntax for defining arrays using bullet points (hyphens). This style enhances readability for lists of items, providing a clear visual structure similar to YAML, while maintaining the overall NEON syntax. ```neon php: date.timezone: Europe/Prague zlib.output_compression: true database: driver: mysql username: root password: beruska92 users: - Dave - Kryten - Rimmer ``` -------------------------------- ### Creating and Modifying UrlImmutable Objects in PHP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/http/readme.md Shows how to instantiate `UrlImmutable` and use its 'wither' methods (e.g., `withUser`, `withPassword`, `withPath`) to create new `UrlImmutable` instances with modified components, rather than altering the original object. The example demonstrates changing user, password, and path. ```php use \Packetery\Nette\Http\UrlImmutable; $url = new UrlImmutable( 'http://john:xyz%2A12@nette.org:8080/en/download?name=param#footer' ); $newUrl = $url ->withUser('') ->withPassword('') ->withPath('/cs/'); echo $newUrl; // 'http://nette.org:8080/cs/?name=param#footer' ``` -------------------------------- ### Defining NEON Sequences in Block Notation Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/neon/readme.md This NEON snippet demonstrates a sequence (equivalent to a PHP indexed array) using block notation. Each item in the sequence starts with a hyphen `-` followed by a space. This format is used for lists of values where order is important. ```NEON - Cat - Dog - Goldfish ``` -------------------------------- ### Chaining Transformations, Assertions, and Casting in PHP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/schema/readme.md This example illustrates how `transform()` can be chained with `assert()` and `castTo()`, with operations executed in the order they are declared. This allows for complex sequences of type conversion, validation, and data modification. ```php Expect::type('string|int') ->castTo('string') ->assert('ctype_lower', 'All characters must be lowercased') ->transform(fn(string $s) => strtoupper($s)); // conversion to uppercase ``` -------------------------------- ### Nesting Schemas with Expect::anyOf() in PHP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/schema/readme.md This example shows that `Expect::anyOf()` can accept other schemas as its parameters, allowing for more complex validation rules where an element can match any of several defined schema types. ```php $schema = Expect::listOf( Expect::anyOf(Expect::string(), true, null), ); $processor->process($schema, ['foo', true, null, 'bar']); // OK $processor->process($schema, [123]); // ERROR ``` -------------------------------- ### Defining Data Structures with Expect::structure() in PHP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/schema/readme.md These examples demonstrate how to define structured data with `Expect::structure()`, specifying required and optional properties. It also shows how `skipDefaults()` can be used to omit properties with only their default values from the output. ```php $schema = Expect::structure([ 'required' => Expect::string()->required(), 'optional' => Expect::string(), // the default value is null ]); $processor->process($schema, ['optional' => '']); // ERROR: option 'required' is missing $processor->process($schema, ['required' => 'foo']); // OK, returns {'required' => 'foo', 'optional' => null} ``` ```php $schema = Expect::structure([ 'required' => Expect::string()->required(), 'optional' => Expect::string(), ])->skipDefaults(); $processor->process($schema, ['required' => 'foo']); // OK, returns {'required' => 'foo'} ``` -------------------------------- ### Loading PHP File from File Content Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/php-generator/readme.md This example shows how to load an entire `PhpFile` object from the content of a PHP file. This allows parsing and manipulating a complete PHP file, including multiple classes or namespaces, and requires `nikic/php-parser`. ```PHP $file = \Packetery\Nette\PhpGenerator\PhpFile::fromCode(file_get_contents('classes.php')); ``` -------------------------------- ### Defining Maximum String Length in PHP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/schema/readme.md This example demonstrates how to set only a maximum character length for a string property using the `max()` method. It allows for flexible length constraints where only an upper bound is necessary. ```php // string, maximum 20 characters Expect::string()->max(20); ``` -------------------------------- ### NEON Configuration with Unquoted Keys and Values Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/neon/readme.md This NEON example demonstrates the flexibility of omitting quotes for keys and string values, unlike strict JSON. It shows a more concise representation of the configuration while maintaining readability, where string values like 'Europe/Prague' and 'mysql' are unquoted. ```neon { php: { date.timezone: Europe/Prague, zlib.output_compression: true }, database: { driver: mysql, username: root, password: beruska92 }, users: [ Dave, Kryten, Rimmer ] } ``` -------------------------------- ### Creating PHP Interfaces and Traits Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/php-generator/readme.md This example demonstrates how to programmatically create new PHP interfaces and traits using the `ClassType` factory methods. `ClassType::interface()` is used for interfaces, and `ClassType::trait()` for traits, similar to how `ClassType::class()` creates a class. ```php $interface = \Packetery\Nette\PhpGenerator\ClassType::interface('MyInterface'); $trait = \Packetery\Nette\PhpGenerator\ClassType::trait('MyTrait'); // in a similar way $class = \Packetery\Nette\PhpGenerator\ClassType::class('MyClass'); ``` -------------------------------- ### PHP Array Equivalent of NEON Block Mapping Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/neon/readme.md This PHP code block shows the equivalent associative array representation for the NEON block mapping example. It illustrates how NEON's `key: value` syntax directly translates to PHP's `key => value` array structure, making it easy to understand the data's structure in both formats. ```PHP [ // PHP 'street' => '742 Evergreen Terrace', 'city' => 'Springfield', 'country' => 'USA', ] ``` -------------------------------- ### Retrieving All HTTP Request Headers - PHP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/http/readme.md This snippet demonstrates how to retrieve all HTTP headers from an `httpRequest` object as an associative array. It then shows an example of accessing a specific header, 'Content-Type', from the returned array. ```php $headers = $httpRequest->getHeaders(); echo $headers['Content-Type']; ``` -------------------------------- ### PHP Array Equivalent of NEON Block Sequence Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/neon/readme.md This PHP code block shows the equivalent indexed array representation for the NEON sequence example. It demonstrates how NEON's `- item` syntax directly translates to PHP's simple array list, providing a clear comparison of data structures. ```PHP [ // PHP 'Cat', 'Dog', 'Goldfish', ] ``` -------------------------------- ### Output of Generated PHP File Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/php-generator/readme.md This is the resulting PHP code generated by the `PhpFile` example. It includes the file comment, strict types declaration, a namespace, a class, and a global function, demonstrating the structure produced by Nette PhpGenerator. ```PHP min(10)->max(20); ``` -------------------------------- ### Generating PHP Elements with Bodies from Reflection Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/php-generator/readme.md This example shows how to generate `ClassType` and `GlobalFunction` objects, including their method and function bodies, from existing code using reflection. This functionality requires the `nikic/php-parser` library to parse the source code. ```PHP $class = \Packetery\Nette\PhpGenerator\ClassType::withBodiesFrom(MyClass::class); $function = \Packetery\Nette\PhpGenerator\GlobalFunction::withBodyFrom('dump'); ``` -------------------------------- ### Retrieving HTTP Request Method in Nette HTTP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/http/readme.md This PHP code illustrates how to obtain the HTTP method (e.g., GET, POST, HEAD, PUT) used for the current request. The `getMethod()` method of the `Nette\Http\Request` object returns the method as a string. ```php echo $httpRequest->getMethod(); // GET, POST, HEAD, PUT ``` -------------------------------- ### Detecting Preferred Language from HTTP Request - PHP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/http/readme.md This snippet illustrates how to detect the user's preferred language based on the `Accept-Language` HTTP header. It takes an array of supported application languages and returns the best match, or `null` if no match is found. The example demonstrates a browser's `Accept-Language` header and the method's output. ```php // Header sent by browser: Accept-Language: cs,en-us;q=0.8,en;q=0.5,sl;q=0.3 $langs = ['hu', 'pl', 'en']; // languages supported in application echo $httpRequest->detectLanguage($langs); // en ``` -------------------------------- ### Multi-line NEON Inline Mapping with Indentation Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/neon/readme.md This example shows an inline NEON mapping spread across multiple lines, demonstrating that indentation within the curly braces does not alter the structure. Elements can be separated by newlines or commas, providing flexibility in formatting while maintaining the inline mapping's compact nature. ```NEON { street: 742 Evergreen Terrace city: Springfield, country: USA } ``` -------------------------------- ### Creating PHP Closures Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/php-generator/readme.md This example illustrates how to generate a PHP closure (anonymous function) using the `Closure` class. It covers setting the closure's body, defining its parameters, and adding `use` variables, including passing them by reference. ```php $closure = new \Packetery\Nette\PhpGenerator\Closure; $closure->setBody('return $a + $b;'); $closure->addParameter('a'); $closure->addParameter('b'); $closure->addUse('c') ->setReference(); echo $closure; // or use PsrPrinter for output compatible with PSR-2 / PSR-12 // echo (new \Packetery\Nette\PhpGenerator\PsrPrinter)->printClosure($closure); ``` -------------------------------- ### Measuring Execution Time with Tracy Debugger timer() (PHP) Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/tracy/tracy/readme.md Illustrates how to use Debugger::timer() to measure the execution time of code segments with microsecond precision. Calling timer() without arguments starts the stopwatch, and calling it again returns the elapsed time. ```PHP Debugger::timer(); // sweet dreams my cherrie sleep(2); $elapsed = Debugger::timer(); // $elapsed = 2 ``` -------------------------------- ### Initializing Nette DI Container in PHP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/di/readme.md This snippet demonstrates how to initialize the Nette DI Container using `ContainerLoader`. It loads the configuration from a NEON file and caches the generated container for performance, ensuring the configuration is processed only once. ```PHP $loader = new \Packetery\Nette\DI\ContainerLoader(__DIR__ . '/temp'); $class = $loader->load(function($compiler) { $compiler->loadConfig(__DIR__ . '/config.neon'); }); $container = new $class; ``` -------------------------------- ### Non-Recursively Searching for Files with Nette Finder in PHP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/finder/readme.md This PHP example shows how to find files matching a mask (e.g., `*.txt`) only within a specified directory (`$dir`) without traversing any subdirectories. The `->in()` method is used instead of `->from()` for this non-recursive search, limiting the search scope to the immediate directory. ```php Finder::findFiles('*.txt')->in($dir) ``` -------------------------------- ### Getting Session Section (Presenter) - PHP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/http/readme.md This snippet shows how to obtain a session section directly from a Nette Presenter instance. When called within a Presenter, the `getSession()` method simplifies access to session sections, ensuring that each part of the application can manage its own session data without conflicts. ```PHP // $this is Presenter $section = $this->getSession('unique name'); ``` -------------------------------- ### Adding HTTP Response Header (Non-Overwriting) - PHP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/http/readme.md This snippet illustrates how to add an HTTP header without overwriting existing headers of the same name, using the `addHeader()` method. This is useful for headers that can have multiple values, such as 'Accept'. The example adds 'application/json' and 'application/xml' to the 'Accept' header. ```php $httpResponse->addHeader('Accept', 'application/json'); $httpResponse->addHeader('Accept', 'application/xml'); ``` -------------------------------- ### Handling Single File Uploads in Nette HTTP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/http/readme.md This PHP example shows how to access a single uploaded file using `getFile()` from the `Nette\Http\Request` object. It checks if a file was actually uploaded and demonstrates how to retrieve its original and sanitized names. The method returns a `Nette\Http\FileUpload` object. ```php $file = $httpRequest->getFile('avatar'); if ($file->hasFile()) { // was any file uploaded? $file->getName(); // name of the file sent by user $file->getSanitizedName(); // the name without dangerous characters } ``` -------------------------------- ### HTML Multiple File Upload Input Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/http/readme.md This HTML snippet defines a file input that allows multiple file selections using the `multiple` attribute and array notation (`[]`) in the name. This setup enables users to upload several files under a single logical group, which will be received as an array of `FileUpload` instances on the server. ```html ``` -------------------------------- ### Configuring Nette DI Services with Neon Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/di/readme.md This configuration snippet, written in Neon, shows how to declare services for Nette DI. It instructs Nette DI to automatically instantiate `FileLogger` (with a constructor argument), `SendMailMailer`, and `NewsletterManager`, handling their dependencies automatically. ```Neon services: - FileLogger( log.txt ) - SendMailMailer - NewsletterManager ``` -------------------------------- ### Casting Schema Structure to Class With Constructor (PHP 8) Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/schema/readme.md This example demonstrates casting a validated schema structure to a class with a constructor, specifically leveraging PHP 8's named parameters. The structure's elements are passed as named arguments to the class constructor, facilitating direct object instantiation. ```php class Info { public function __construct( public bool $processRefund, public int $refundAmount, ) { } } // creates $obj = new Info(processRefund: ..., refundAmount: ...) ``` -------------------------------- ### Configuring URL Filters in RequestFactory - PHP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/http/readme.md This snippet demonstrates how to configure URL filters within the `RequestFactory` to clean up URLs. It shows examples of removing spaces from the path, stripping trailing punctuation from the URL, and cleaning duplicated slashes in the path, which is a default filter. These filters help sanitize URLs from malformed characters. ```php // remove spaces from path $requestFactory->urlFilters['path']['%20'] = ''; // remove dot, comma or right parenthesis form the end of the URL $requestFactory->urlFilters['url']['[.,)]$'] = ''; // clean the path from duplicated slashes (default filter) $requestFactory->urlFilters['path']['/{2,}'] = '/'; ``` -------------------------------- ### Integrating Tracy with Non-Standard PHP Session Handlers Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/tracy/tracy/readme.md This advanced PHP snippet outlines the process for integrating Tracy when using a non-standard session handler. It involves enabling Tracy early, then initializing your custom session handler (e.g., `session_start()`), and finally calling `Debugger::dispatch()` to inform Tracy that the session is ready for use. ```PHP Debugger::setSessionStorage(new \Packetery\Tracy\NativeSession); Debugger::enable(); // initialize session handler session_start(); Debugger::dispatch(); ``` -------------------------------- ### Searching Files with Character Range Mask in Nette Finder in PHP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/finder/readme.md This PHP example demonstrates using character ranges in a file mask, similar to regular expressions. It searches for `*.txt` files that contain at least one digit (`[0-9]`) anywhere in their name, allowing for more precise pattern matching based on character sets. ```php Finder::findFiles('*[0-9]*.txt') ``` -------------------------------- ### Implementing a Custom Logger with Tracy in PHP and NEON Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/tracy/tracy/readme.md Shows how to create a custom logger by implementing the `ILogger` interface to handle errors and exceptions, and then activate it programmatically in PHP or via NEON configuration within the Nette Framework. ```PHP use \Packetery\Tracy\ILogger; class SlackLogger implements ILogger { public function log($value, $priority = ILogger::INFO) { // sends a request to Slack } } ``` ```PHP \Packetery\Tracy\Debugger::setLogger(new SlackLogger); ``` ```NEON services: tracy.logger: SlackLogger ``` -------------------------------- ### Illustrating Manual Class Loading in PHP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/robot-loader/readme.md This snippet demonstrates the traditional, manual way of including PHP files using `require_once`. It highlights the problem that RobotLoader aims to solve by automating this process, reducing boilerplate code and improving maintainability. ```PHP require_once 'Utils/Page.php'; require_once 'Utils/Style.php'; require_once 'Utils/Paginator.php'; ... ``` -------------------------------- ### Configuring and Registering Nette RobotLoader for Autoloading Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/robot-loader/readme.md This PHP snippet shows the basic configuration of RobotLoader. It initializes a new `RobotLoader` instance, specifies the directories to be scanned for classes, sets a temporary directory for caching, and then registers the autoloader to enable automatic class loading. ```PHP $loader = new \Packetery\Nette\Loaders\RobotLoader; // directories to be indexed by RobotLoader (including subdirectories) $loader->addDirectory(__DIR__ . '/app'); $loader->addDirectory(__DIR__ . '/libs'); // use 'temp' directory for cache $loader->setTempDirectory(__DIR__ . '/temp'); $loader->register(); // Run the RobotLoader ``` -------------------------------- ### Generating URLs with Nette\Http\Url in PHP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/http/readme.md This snippet demonstrates how to construct a URL programmatically using the `\Packetery\Nette\Http\Url` class. It shows setting the scheme, host, path, and adding a query parameter, then echoing the resulting URL string. ```php use \Packetery\Nette\Http\Url; $url = new Url; $url->setScheme('https') ->setHost('localhost') ->setPath('/edit') ->setQueryParameter('foo', 'bar'); echo $url; // 'https://localhost/edit?foo=bar' ``` -------------------------------- ### Getting Session Section (Global) - PHP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/http/readme.md This snippet demonstrates how to retrieve a specific session section using the global session manager. Each section provides an isolated storage space within the session, preventing name collisions between different application components. The `getSession()` method requires a unique string name for the desired section. ```PHP $section = $session->getSession('unique name'); ``` -------------------------------- ### Adding Custom Assertion with Description in PHP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/schema/readme.md This example shows how to provide a custom description for an assertion, which will be included in the error message if the assertion fails. This improves the clarity and helpfulness of validation error messages for developers. ```php $schema = Expect::arrayOf('string') ->assert($countIsEven, 'Even items in array'); $processor->process($schema, ['a', 'b', 'c']); // Failed assertion "Even items in array" for item with value array. ``` -------------------------------- ### Creating and Configuring a PHP File with Nette PhpGenerator Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/php-generator/readme.md This snippet demonstrates how to create a new PHP file using `PhpFile`, add comments, enable strict types, and define classes and functions within it. It also shows alternative ways to add elements via namespaces and how to print the file content. ```PHP $file = new \Packetery\Nette\PhpGenerator\PhpFile; $file->addComment('This file is auto-generated.'); $file->setStrictTypes(); // adds declare(strict_types=1) $class = $file->addClass('Foo\A'); $function = $file->addFunction('Foo\foo'); // or // $namespace = $file->addNamespace('Foo'); // $class = $namespace->addClass('A'); // $function = $namespace->addFunction('foo'); echo $file; // or use PsrPrinter for output compatible with PSR-2 / PSR-12 // echo (new \Packetery\Nette\PhpGenerator\PsrPrinter)->printFile($file); ``` -------------------------------- ### Using a Generated Factory in PHP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/di/readme.md This PHP class demonstrates how to use a factory generated by Nette. The `IBarFactory` is injected into the `Foo` class's constructor, and its `create` method is then called to obtain new instances of the `Bar` object. ```PHP class Foo { private $barFactory; function __construct(IBarFactory $barFactory) { $this->barFactory = $barFactory; } function bar() { $bar = $this->barFactory->create(); } } ``` -------------------------------- ### Nesting Schemas with Expect::arrayOf() in PHP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/schema/readme.md This example demonstrates the flexibility of `Expect::arrayOf()` by allowing a schema itself to be passed as a parameter, enabling the validation of arrays containing elements that conform to a more complex nested schema. ```php Expect::arrayOf(Expect::bool()) ``` -------------------------------- ### Registering a Factory Interface in Nette NEON (Short Form) Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/di/readme.md This NEON configuration shows the concise way to register a factory interface in the Nette DI container. Nette automatically detects that it's an interface and generates the necessary implementation for the factory. ```NEON services: - IBarFactory ``` -------------------------------- ### Casting Scalar to String in PHP Schema Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/schema/readme.md This example demonstrates how to cast a successfully validated scalar value to a string type using the `castTo()` method. This is useful for ensuring that the final output data type matches specific requirements. ```php Expect::scalar()->castTo('string'); ``` -------------------------------- ### Registering a Basic Service in Nette NEON Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/di/readme.md This NEON configuration demonstrates the simplest way to register a service in the Nette DI container. By just specifying the class name, Nette automatically resolves and injects any dependencies declared in the service's constructor. ```NEON services: manager: NewsletterManager ``` -------------------------------- ### Implementing Inject Methods and Annotations in PHP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/di/readme.md This PHP class illustrates two ways to receive dependencies when the `inject: yes` directive is enabled: through `inject*` methods (e.g., `injectService1`) and by assigning to public variables with the `@inject` annotation (e.g., `$service2`). ```PHP class FooClass { private $service1; // 1) inject* method: public function injectService1(Service1 $service) { $this->service1 = $service1; } // 2) Assign to the variable with the @inject annotation: /** @inject @var Service2 */ public $service2; } ``` -------------------------------- ### Generating PHP Anonymous Classes Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/php-generator/readme.md This example shows how to create an anonymous class by passing `null` as the name to the `ClassType` constructor. The generated anonymous class can then be instantiated and used like any other class, often for inline, single-use implementations. ```php $class = new \Packetery\Nette\PhpGenerator\ClassType(null); $class->addMethod('__construct') ->addParameter('foo'); echo '$obj = new class ($val) ' . $class . ';'; ``` -------------------------------- ### Instantiating and Using a Manual DI Container in PHP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/di/readme.md This snippet illustrates how to instantiate the manually created `Container` class. It then demonstrates how to retrieve a fully configured `NewsletterManager` instance from the container and use it to perform its primary function. ```PHP $container = new Container; $manager = $container->createNewsletterManager(); $manager->distribute(...); ``` -------------------------------- ### Adding Custom Assertion for Array Count in PHP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/schema/readme.md This example demonstrates adding a custom validation rule using `assert()` with a callable function. It validates that the count of elements in an array is even, showing how to apply custom logic for schema validation. ```php $countIsEven = fn($v) => count($v) % 2 === 0; $schema = Expect::arrayOf('string') ->assert($countIsEven); // the count must be even $processor->process($schema, ['a', 'b']); // OK $processor->process($schema, ['a', 'b', 'c']); // ERROR: 3 is not even ``` -------------------------------- ### Enabling Tracy PHP Debugger Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/tracy/tracy/readme.md This PHP code snippet activates the Tracy debugger. It first imports the `Debugger` class and then calls its static `enable()` method. This should be placed early in the application's bootstrap, ideally after Composer's autoloader and before any output is sent to the browser, to ensure comprehensive error reporting and the display of the Debugger Bar. ```PHP use \Packetery\Tracy\Debugger; Debugger::enable(); ``` -------------------------------- ### Deprecating Schema Properties in PHP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/schema/readme.md This example illustrates how to mark a schema property as deprecated using the `deprecated()` method, optionally providing a custom message. Deprecation notices are not errors but warnings, which can be retrieved using `$processor->getWarnings()` after processing the schema. ```php $schema = Expect::structure([ 'old' => Expect::int()->deprecated('The item %path% is deprecated'), ]); $processor->process($schema, ['old' => 1]); // OK $processor->getWarnings(); // ["The item 'old' is deprecated"] ``` -------------------------------- ### Implementing a Manual DI Container in PHP Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/nette/di/readme.md This PHP class demonstrates a manually implemented Dependency Injection container. It showcases lazy loading of services (`FileLogger`, `SendMailMailer`) and how to assemble and provide instances of `NewsletterManager` with its required dependencies. ```PHP class Container { private $logger; private $mailer; function getLogger() { if (!$this->logger) { $this->logger = new FileLogger('log.txt'); } return $this->logger; } function getMailer() { if (!$this->mailer) { $this->mailer = new SendMailMailer; } return $this->mailer; } function createNewsletterManager() { return new NewsletterManager($this->getMailer(), $this->getLogger()); } } ``` -------------------------------- ### Optimizing Tracy Loader Placement in HTML Template Source: https://github.com/zasilkovna/woocommerce/blob/pre-release/deps/tracy/tracy/readme.md This HTML snippet demonstrates the recommended placement for `\Packetery\Tracy\Debugger::renderLoader()` within your web page's `
` section. Placing it before other blocking scripts, such as external JavaScript libraries, helps to ensure Tracy loads faster and doesn't impede page rendering. ```HTML