### Complete OpenSSL encryption example Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/standard-filters.md A comprehensive example of encrypting text using the OpenSSL adapter. It sets up the filter with keys and a passphrase, performs the encryption, retrieves the envelope key, and prints the encrypted content. Ensure OpenSSL extension is enabled and keys are valid. ```php // Use openssl and provide a private key $filter = new Laminas\Filter\Encrypt([ 'adapter' => 'openssl', 'passphrase' => 'enter here the passphrase for the private key', 'private' => '/path/to/mykey/private.pem', 'public' => '/public/key/path/public.pem' ]); $encrypted = $filter->filter('text_to_be_encoded'); $envelope = $filter->getEnvelopeKey(); print $encrypted; // For decryption look at the Decrypt filter ``` -------------------------------- ### RenameUpload Usage Examples Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/file.md Examples demonstrating how to use LaminasFilterFileRenameUpload for various file manipulation tasks. ```APIDOC ## Laminas\Filter\File\RenameUpload ### Description `Laminas\Filter\File\RenameUpload` can be used to rename or move an uploaded file to a new path. The filter will only attempt to operate on uploaded files. ### Supported Options - `target` (string; default: `*`): Target directory or full filename path. - `overwrite` (boolean; default: `false`): Shall existing files be overwritten? - `randomize` (boolean; default: `false`): Shall target files have a random postfix attached? - `use_upload_name` (boolean; default: `false`): When true, this filter will use `$_FILES['name']` as the target filename. - `use_upload_extension` (boolean; default: `false`): When true, the uploaded file will maintain its original extension if not specified. ### Usage Examples **Move all filtered files to a different directory:** ```php // 'target' option is assumed if param is a string $filter = new LaminasFilterFileRenameUpload(['target_directory' => '/tmp/']); echo $filter->filter('./myfile.txt'); // File has been moved to '/tmp/myfile.txt' ``` **Rename all filtered files to a new name:** ```php $filter = new LaminasFilterFileRenameUpload(['rename_to' => 'newfile.txt'); echo $filter->filter('./myfile.txt'); // File has been renamed to 'newfile.txt' ``` **Move to a new path, and randomize file names:** ```php $filter = new LaminasFilterFileRenameUpload([ 'match' => '/tmp/*.txt', 'randomize' => true, ]); echo $filter->filter('./myfile.txt'); // File has been renamed to '/tmp/newfile_4b3403665fea6.txt' ``` **Configure different options for several possible source files:** ```php $filter = new LaminasFilterFileRenameUpload([ [ 'match' => '*.pdf', 'target_directory' => '/pdf-files/', 'rename_to' => 'newfileA.pdf', 'overwrite' => true, ], [ 'match' => '*.txt', 'target_directory' => '/text-files/', 'rename_to' => 'newfileB.txt', 'randomize' => true, ], ]); echo $filter->filter('fileA.txt'); // File has been renamed to '/dest1/newfileA.txt' echo $filter->filter('fileB.txt'); // File has been renamed to '/dest2/newfileB_4b3403665fea6.txt' ``` ### Security Considerations > **WARNING: Using the upload Name is unsafe** > Be **very** careful when using the `use_upload_name` option. For instance, extremely bad things could happen if you were to allow uploaded `.php` files (or other CGI files) to be moved into the `DocumentRoot`. It is generally a better idea to supply an internal filename to avoid security risks. ``` -------------------------------- ### Custom Plugin Manager Setup for StaticFilter Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/intro.md Demonstrates how to set a completely new `FilterPluginManager` instance for `StaticFilter`, useful for managing custom filter loading. ```php StaticFilter::setPluginManager(new MyFilterPluginManager()); ``` -------------------------------- ### PHP FilterProviderInterface Example Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/application-integration/providing-filters-via-modules.md Demonstrates the structure for a Module class to provide filters via the getFilterConfig() method, returning Laminas-servicemanager compatible configuration. ```php namespace App\Module; use Laminas\ModuleManager\Feature\FilterProviderInterface; class Module implements FilterProviderInterface { /** * @return array */ public function getFilterConfig() { return [ 'factories' => [ // Example: Registering a custom filter 'MyCustomFilter' => function($container) { // Logic to create and return your filter return new AppFilterMyCustomFilter($container->get('some_dependency')); }, ], // Other filter configurations can go here ]; } } ``` -------------------------------- ### StringPrefix Filter - Basic Usage Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/standard-filters.md Provides an example of the StringPrefix filter, which adds a specified prefix to scalar string values. It demonstrates how to initialize the filter with a prefix and apply it to a string. ```php $filter = new Laminas\Filter\StringPrefix([ 'prefix' => 'PHP-', ]); echo $filter->filter('MidCentral'); ``` -------------------------------- ### Laminas Filter Boolean Type Configuration Examples Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/standard-filters.md Provides examples of configuring the Laminas Filter Boolean to handle specific types for conversion to boolean. It demonstrates using constants, arrays, and string representations for type configuration. ```php // converts 0 to false $filter = new Laminas\Filter\Boolean(Laminas\Filter\Boolean::TYPE_INTEGER); ``` ```php // converts 0 and '0' to false $filter = new Laminas\Filter\Boolean( Laminas\Filter\Boolean::TYPE_INTEGER + Laminas\Filter\Boolean::TYPE_ZERO_STRING ); ``` ```php // converts 0 and '0' to false $filter = new Laminas\Filter\Boolean([ 'type' => [ Laminas\Filter\Boolean::TYPE_INTEGER, Laminas\Filter\Boolean::TYPE_ZERO_STRING, ], ]); ``` ```php // converts 0 and '0' to false $filter = new Laminas\Filter\Boolean([ 'type' => [ 'integer', 'zero', ], ]); ``` -------------------------------- ### Get Filter Chain Instance with Laminas Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/filter-chains.md Demonstrates how to obtain a FilterChain instance using LaminasFilterFilterPluginManager. It shows manual instantiation, retrieval from the plugin manager, and building with configuration. ```php assert($container instanceof Psr\Container\ContainerInterface); $pluginManager = $container->get(Laminas\Filter\FilterPluginManager::class); // Create a Filter Chain instance manually: $chain = new Laminas\Filter\FilterChain($pluginManager); // Fetch an empty filter chain from the plugin manager $chain = $pluginManager->get(Laminas\Filter\FilterChain::class); // Build a ready-to-use filter chain via the plugin manager $chain = $pluginManager->build(Laminas\Filter\FilterChain::class, [ // ...(Filter Chain Configuration)) ]); ``` -------------------------------- ### StaticFilter Execution with Constructor Arguments Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/intro.md Demonstrates how to pass constructor arguments to a filter when using `StaticFilter::execute()`. This example sets the `quotestyle` for the `HtmlEntities` filter. ```php echo StaticFilter::execute( '"', 'HtmlEntities', ['quotestyle' => ENT_QUOTES] ); ``` -------------------------------- ### StringToLower Filter - Basic Usage Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/standard-filters.md Shows the basic functionality of the StringToLower filter, which converts input strings to lowercase. This example demonstrates initializing the filter and applying it to an uppercase string. ```php $filter = new Laminas\Filter\StringToLower(); print $filter->filter('SAMPLE'); // returns "sample" ``` -------------------------------- ### StringSuffix Filter - Basic Usage Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/standard-filters.md Illustrates the basic usage of the StringSuffix filter, which appends a specified suffix to scalar string values. The example shows filter initialization with a suffix and its application to a string. ```php $filter = new Laminas\Filter\StringSuffix([ 'suffix' => '-PHP', ]); echo $filter->filter('MidCentral'); ``` -------------------------------- ### Improve Type Inference with Generics Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/writing-filters.md Illustrates using generics with `FilterInterface` to enhance type inference for static analysis tools like Psalm or PHPStan. This example narrows the return type of the filter. ```php use Laminas\Filter\FilterInterface; /** @implements FilterInterface> */ final class MyFilter implements FilterInterface { public function filter(mixed $value): mixed { if (! is_bool($value)) { return $value; } return $value ? 1 : 0; } public function __invoke(mixed $value): mixed { return $this->filter($value); } } ``` -------------------------------- ### Implement Custom Filter with Laminas FilterInterface (PHP) Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/writing-filters.md Demonstrates how to create a custom filter class by implementing the `LaminasFilterFilterInterface`. This interface requires a single `filter()` method for value transformation. The example shows a basic structure for such a class. ```php namespace Application\Filter; use Laminas\Filter\FilterInterface; class MyFilter implements FilterInterface { public function filter($value) { // perform some transformation upon $value to arrive on $valueFiltered return $valueFiltered; } } ``` -------------------------------- ### LaminasFilterMonthSelect: Basic usage Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/standard-filters.md Provides an example of using LaminasFilterMonthSelect to format month and year values into a 'YYYY-MM' string. This filter is useful for standardizing date inputs. ```php $filter = new Laminas\Filter\MonthSelect(); print $filter->filter(['month' => '2', 'year' => '2012']); ``` -------------------------------- ### Retrieve Filters using Laminas Filter Plugin Manager Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/plugin-manager.md Shows how to retrieve filter instances from the `LaminasFilterFilterPluginManager` using its `get()` method. Filters can be fetched by their fully qualified class name or by a registered alias. ```php $filter = $filterPluginManager->get(Laminas\Filter\StringTrim::class); ``` ```php $filter = $filterPluginManager->get('stringtrim'); $filter = $filterPluginManager->get('stringTrim'); $filter = $filterPluginManager->get('StringTrim'); ``` -------------------------------- ### Manage Inflection Rules in Laminas Filter Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/inflector.md Provides examples for retrieving all rules or rules for a specific variable, fetching a single rule within a chain, and clearing all registered rules for a Laminas\Filter\Inflector instance. ```php getRules(); // Get rules for a specific variable $variableRules = $inflector->getRules('variableName'); // Fetch a single rule for a variable in a filter chain $specificRule = $inflector->getRule('variableName', 0); // Fetch the first rule // Clear all registered rules $inflector->clearRules(); ``` -------------------------------- ### Basic ToString Filter Usage (PHP) Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/standard-filters.md Shows the basic usage of the LaminasFilterToString filter, which casts Stringable objects or scalar values to strings. Includes examples of filtering integers and arrays. ```php $filter = new \Laminas\Filter\ToString(); $filter->filter(123); // "123" $filter->filter(['id' => 100, 'roles' => null]); // ['id' => "100", 'roles' => null] ``` -------------------------------- ### Double Filtering Example: UnderscoreToCamelCase and CamelCaseToUnderscore Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/basic-usage.md Illustrates a double filtering scenario using Laminas filters. It shows the conversion from underscore_case to CamelCase and then back to underscore_case. It also highlights that reversing the process might not always yield the exact original input. ```php $original = 'my_original_content'; // Attach a filter $filter = new Laminas\Filter\Word\UnderscoreToCamelCase(); $filtered = $filter->filter($original); // Use it's opposite $filter2 = new Laminas\Filter\Word\CamelCaseToUnderscore(); $filtered = $filter2->filter($filtered) ``` -------------------------------- ### Get BlockCipher Encryption Details (PHP) Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/standard-filters.md Retrieves the current encryption configuration of the BlockCipher filter, including key iteration, algorithm, hash, and the encryption key itself. Requires the filter to be initialized and the key to be set. ```php $filter = new Laminas\Filter\Encrypt(['adapter' => 'BlockCipher']); $filter->setKey('encryption key'); var_dump($filter->getEncryption()); // Will print: //array(4) { // ["key_iteration"]=> // int(5000) // ["algorithm"]=> // string(3) "aes" // ["hash"]=> // string(6) "sha256" // ["key"]=> // string(14) "encryption key" //} ``` -------------------------------- ### Configure Input Filters in a Laminas Form in PHP Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/plugin-manager.md This example shows how to define input filter specifications within a Laminas Form class. It utilizes filters like `StripTags` and `StringTrim`, and validators like `StringLength`, which are automatically retrieved and applied by the filter plugin manager. ```php namespace Album\Form; use Laminas\Filter\StringTrim; use Laminas\Filter\StripTags; use Laminas\Form\Element\Text; use Laminas\Form\Form; use Laminas\InputFilter\InputFilterProviderInterface; use Laminas\Validator\StringLength; final class AlbumForm extends Form implements InputFilterProviderInterface { public function init(): void { // Add form elements $this->add([ 'name' => 'title', 'type' => Text::class, 'options' => [ 'label' => 'Title', ], ]); // … } public function getInputFilterSpecification(): array { return [ // Add inputs [ 'name' => 'title', 'filters' => [ ['name' => StripTags::class], ['name' => StringTrim::class], ], 'validators' => [ [ 'name' => StringLength::class, 'options' => [ 'min' => 1, 'max' => 100, ], ], ], ], // … ]; } } ``` -------------------------------- ### Define a Custom Filter in PHP Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/plugin-manager.md This snippet defines a custom filter class that implements the LaminasFilterFilterInterface. It serves as a basic example of a filter that can be used with the filter plugin manager. No external dependencies are required for this basic implementation. ```php final class ExampleFilter implements Laminas\Filter\FilterInterface { public function filter(mixed $value): mixed { // … } } ``` -------------------------------- ### Fetch a Custom Filter Using the Manager in PHP Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/plugin-manager.md This example demonstrates how to retrieve a custom filter instance from the filter plugin manager using its class name. The manager automatically instantiates the filter using `Laminas\ServiceManager\Factory\InvokableFactory`. Note that an alias is not automatically created. ```php $filter = $filterPluginManager->get(ExampleFilter::class); ``` -------------------------------- ### Laminas HtmlEntities Filter: Set and Get Quote Style Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/standard-filters.md Demonstrates how to instantiate the HtmlEntities filter and utilize the setQuoteStyle and getQuoteStyle methods to manage quote handling. The setQuoteStyle method accepts constants like ENT_QUOTES. ```php $filter = new Laminas\Filter\HtmlEntities(); $filter->setQuoteStyle(ENT_QUOTES); print $filter->getQuoteStyle(ENT_QUOTES); ``` -------------------------------- ### Encrypt with OpenSSL using private key Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/standard-filters.md Demonstrates initializing the Laminas Encrypt filter with the OpenSSL adapter and a private key. It also shows how to set the public key separately. Requires the OpenSSL extension and valid key paths. ```php // Use openssl and provide a private key $filter = new Laminas\Filter\Encrypt([ 'adapter' => 'openssl', 'private' => '/path/to/mykey/private.pem', ]); // Add the private key separately: $filter->setPublicKey('/public/key/path/public.pem'); ``` -------------------------------- ### Initializing Compress Filter with Options Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/standard-filters.md Demonstrates how to initialize the Laminas Compress filter with an adapter and custom options, such as 'blocksize' for the Bz2 adapter. Options can be provided as an array or a Traversable object. ```php $filter = new Laminas\Filter\Compress([ 'adapter' => 'Bz2', 'options' => [ 'blocksize' => 8, ], ]); ``` -------------------------------- ### Instantiate and Use Filters Directly (PHP) Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/migration/preparing-for-v3.md The StaticFilter class is removed. Filters should now be instantiated directly using 'new' or obtained via a FilterPluginManager for dependency injection. ```php $filtered = (new \Laminas\Filter\HtmlEntities())('Nuts & Bolts'); ``` ```php $pluginManager = $container->get(\Laminas\Filter\FilterPluginManager::class); $filter = $pluginManager->get(\Laminas\Filter\HtmlEntities::class); $filtered = $filter->filter('A String'); ``` -------------------------------- ### Initializing Decompress Filter Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/standard-filters.md Initializes the Laminas Decompress filter with a specified compression adapter, ready to decompress data. ```php $filter = new Laminas\Filter\Decompress('Bz2'); ``` -------------------------------- ### Set and Get Plugin Manager in Laminas Filter Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/inflector.md Demonstrates how to set a custom Laminas\Filter\FilterPluginManager instance and retrieve the currently active one for use with Laminas\Filter\Inflector. ```php setPluginManager($pluginManager); // Retrieve the current plugin manager $currentPluginManager = $inflector->getPluginManager(); ``` -------------------------------- ### Encrypt with OpenSSL using passphrase and keys Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/standard-filters.md Shows how to encrypt content using the OpenSSL adapter when a passphrase is required for the private key. It includes setting the private key, public key, and passphrase during instantiation. Requires valid keys and the correct passphrase. ```php // Use openssl and provide a private key $filter = new Laminas\Filter\Encrypt([ 'adapter' => 'openssl', 'passphrase' => 'enter here the passphrase for the private key', 'private' => '/path/to/mykey/private.pem', 'public' => '/public/key/path/public.pem' ]); ``` -------------------------------- ### Initialize Laminas Filter Encrypt with Adapters Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/standard-filters.md Demonstrates how to instantiate the Laminas Filter Encrypt class and specify either the 'BlockCipher' or 'openssl' adapter during initialization. This is the primary way to select the desired encryption method. ```php // Use the BlockCipher adapter $filter1 = new Laminas\Filter\Encrypt(['adapter' => 'BlockCipher']); // Use the OpenSSL adapter $filter2 = new Laminas\Filter\Encrypt(['adapter' => 'openssl']); ``` -------------------------------- ### Digits Filter Usage Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/standard-filters.md Shows how the Digits filter removes all non-digit characters from a string, leaving only numeric characters. Examples include processing date-like and text strings. ```php $filter = new Laminas\Filter\Digits(); print $filter->filter('October 2012'); ``` ```php $filter = new Laminas\Filter\Digits(); print $filter->filter('HTML 5 for Dummies'); ``` -------------------------------- ### OpenSSL encryption with Zip compression and options Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/standard-filters.md Shows how to use the OpenSSL adapter with Zip compression, providing specific options for the compression adapter. This allows for more control over the compression process. Ensure OpenSSL extension is enabled and keys are valid. ```php // Compression adatper with options: $filter2 = new Laminas\Filter\Encrypt([ 'adapter' => 'openssl', 'private' => '/path/to/mykey/private.pem', 'public' => '/public/key/path/public.pem', 'package' => true, 'compression' => ['adapter' => 'zip', 'target' => '\usr\tmp\tmp.zip'] ]); ``` -------------------------------- ### PregReplace Filter - Using Setters Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/standard-filters.md Illustrates how to use the setPattern() and setReplacement() methods to configure the PregReplace filter dynamically. This approach is useful for setting multiple patterns and replacements. ```php $filter = new Laminas\Filter\PregReplace(); $filter ->setPattern(array('bob', 'Hi')) ->setReplacement(array('john', 'Bye')); $input = 'Hi bob!'; $filter->filter($input); // returns 'Bye john!' ``` -------------------------------- ### Handle PSR-7 Uploaded Files with Laminas Filter Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/file.md Demonstrates processing PSR-7 uploaded files using LaminasFilterFileRenameUpload. This example iterates through uploaded files from a PSR-7 request and renames them. ```php use Laminas\Filter\File\RenameUpload; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\UploadedFileInterface; $filter = new \Laminas\Filter\File\RenameUpload([ 'target' => './data/uploads/', 'randomize' => true, ]); // @var ServerRequestInterface $request foreach ($request->getUploadedFiles() as $uploadedFile) { // @var UploadedFileInterface $uploadedFile $newFilePath = $filter->filter($uploadedFile); echo $newFilePath; // File has been renamed to './data/uploads/newfile_4b3403665fea6.txt' } ``` -------------------------------- ### Build Filter Chain with Array Configuration Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/filter-chains.md Demonstrates creating a filter chain using an array configuration, specifying filters by name (StringTrim, StringToLower) and providing a callback for string reversal. The output is the reversed, trimmed, and lowercased string. ```php use Laminas\Filter\FilterChain; use Laminas\Filter\StringToLower; use Laminas\Filter\StringTrim; $pluginManager = $container->get(Laminas\Filter\FilterPluginManager::class); $chain = $pluginManager->build(FilterChain::class, [ 'filters' => [ ['name' => StringTrim::class], ['name' => StringToLower::class], ], 'callbacks' => [ ['callback' => static fn (string $value): string => strrev($value)], ], ]); print $chain->filter(' OOF '); // 'foo' ``` -------------------------------- ### Change Target Placeholder Delimiter in Inflector Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/inflector.md This example shows how to customize the placeholder delimiter used by Laminas\Filter\Inflector. By setting 'targetReplacementIdentifier', you can avoid conflicts when your target string contains the default delimiter (':'). ```php $pluginManager = $container->get(LaminasFilterFilterPluginManager::class); $inflector = new LaminasFilterInflector($pluginManager, [ 'target' => '?host:?port/?page.?suffix', 'targetReplacementIdentifier' => '?', 'rules' => [ 'host' => 'example.com', 'port' => '80', 'page' => 'anything', 'suffix' => 'html', ], ]); $inflector->filter(['page' => 'index']); // example.com:80/index.html ``` -------------------------------- ### Allowing Specific Tags with StripTags in PHP Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/standard-filters.md Shows how to configure LaminasFilterStripTags to allow only specific HTML tags, stripping all others. This example allows only the 'a' tag, preserving links while removing other markup. ```php $filter = new Laminas\Filter\StripTags(['allowTags' => ['a']]); $input = "A text with
a link"; print $filter->filter($input); ``` -------------------------------- ### Register Custom Filters with Plugin Manager Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/writing-filters.md Demonstrates registering custom filters with the plugin manager using the `filters` configuration key. This allows filters to be retrieved by FQCN or alias. ```php use Laminas\ServiceManager\Factory\InvokableFactory; return [ 'filters' => [ 'factories' => [ My\Filter\FilterOne::class => InvokableFactory::class, My\Filter\FilterTwo::class => My\Filter\SomeCustomFactory::class, ], 'aliases' => [ 'filterOne' => My\Filter\FilterOne::class, 'filterTwo' => My\Filter\FilterTwo::class, ], ], ]; ``` -------------------------------- ### Decompress Archive to Target Directory using Zip Adapter Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/standard-filters.md Shows how to decompress an archive file into a specified target directory using the Zip adapter. This requires the target directory to exist beforehand. ```php $filter = new Laminas\Filter\Decompress([ 'adapter' => 'Zip', 'options' => [ 'target' => 'C:\\temp', ] ]); $decompressed = $filter->filter('filename.zip'); // Returns true on success, and decompresses the archive file // into the given target directory ``` -------------------------------- ### Add Filters to Chain: Instances and Closures Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/filter-chains.md Shows how to build a filter chain by attaching filter instances (StringTrim, StringToLower) and a closure for string reversal. The input is trimmed, converted to lowercase, and then reversed. ```php use Laminas\Filter\FilterChain; use Laminas\Filter\StringToLower; use Laminas\Filter\StringTrim; $pluginManager = $container->get(Laminas\Filter\FilterPluginManager::class); $chain = $pluginManager->get(FilterChain::class); $chain->attach(new StringTrim()); // directly instantiate the filter $chain->attach($pluginManager->get(StringToLower::class)); $chain->attach(static fn (string $value): string => strrev($value)); print $chain->filter(' OOF '); // 'foo' ``` -------------------------------- ### Basic HTML Entity Encoding with Laminas Filter Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/basic-usage.md This example shows how to use the LaminasFilterHtmlEntities class to encode special characters like ampersand and double quotes into their corresponding HTML entities. ```php $htmlEntities = new Laminas\Filter\HtmlEntities(); echo $htmlEntities->filter('&'); // & echo $htmlEntities->filter('"'); // " ``` -------------------------------- ### Pass Options to Custom Filters using build() Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/plugin-manager.md Explains how to use the `build()` method of the `LaminasFilterFilterPluginManager` to instantiate a filter and pass options to its constructor. This method is useful for filters requiring specific configurations upon creation. ```php $filter = $filterPluginManager->build( ExampleFilter::class, [ // Options for the filter as an associative array ] ); ``` -------------------------------- ### Create Laminas Filter Plugin Manager Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/plugin-manager.md Demonstrates the creation of a `LaminasFilterFilterPluginManager` instance, which is a specialized service manager for filters. It requires a PSR-11 compatible service container, typically `LaminasServiceManagerServiceManager`. ```php $filterPluginManager = new Laminas\Filter\FilterPluginManager( new Laminas\ServiceManager\ServiceManager() ); ``` -------------------------------- ### Laminas ToInt Filter: Basic Usage Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/standard-filters.md Provides an example of using the Laminas ToInt filter to convert a string containing a number into an integer. The filter extracts numeric values from scalar inputs. ```php $filter = new Laminas\Filter\ToInt(); print $filter->filter('-4 is less than 0'); ``` -------------------------------- ### Allowing Specific Attributes with StripTags in PHP Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/standard-filters.md Demonstrates configuring LaminasFilterStripTags to allow specific attributes for allowed tags. This example permits only the 'img' tag and the 'src' attribute for it, stripping other attributes and tags. ```php $filter = new Laminas\Filter\StripTags([ 'allowTags' => ['img'], 'allowAttribs' => ['src'], ]); $input = "A text with
a picture"; print $filter->filter($input); ``` -------------------------------- ### OpenSSL encryption with BZ2 compression Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/standard-filters.md Demonstrates encrypting content with OpenSSL and applying BZ2 compression using the 'compression' option. This reduces the size of the encrypted output. Requires the OpenSSL extension and valid key paths. ```php // Use basic compression adapter $filter1 = new Laminas\Filter\Encrypt([ 'adapter' => 'openssl', 'private' => '/path/to/mykey/private.pem', 'public' => '/public/key/path/public.pem', 'package' => true, 'compression' => 'bz2' ]); ``` -------------------------------- ### Basic Filter Chaining in PHP Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/filter-chains.md Demonstrates creating a FilterChain and attaching two filters (Alpha and StringToLower) to process a username. Filters are applied in the order they are attached. ```php use Laminas\Filter\FilterChain; use Laminas\I18n\Filter\Alpha; use Laminas\Filter\StringToLower; // Create a filter chain and add filters to the chain $filterChain = new FilterChain(); $filterChain ->attach(new Alpha()) ->attach(new StringToLower()); // Filter the username $username = $filterChain->filter($_POST['username']); ``` -------------------------------- ### Get Non-Existing Paths with RealPath Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/standard-filters.md Creates a RealPath filter that can resolve paths even if they do not exist. Useful for determining the final path for a file that will be created. It takes an 'exists' option, which defaults to true. ```php $filter = new Laminas\Filter\RealPath(['exists' => false]); $path = '/www/var/path/../../non/existing/path'; $filtered = $filter->filter($path); // returns '/www/non/existing/path' ``` -------------------------------- ### StripTags Filter Usage Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/standard-filters.md Shows the basic functionality of the StripTags filter to remove HTML and XML tags from a string. It also includes examples of allowing specific tags and attributes, with a warning about security implications. ```php $filter = new Laminas\Filter\StripTags(); print $filter->filter('My content'); // returns "My content" ``` ```php $filter = new Laminas\Filter\StripTags(); print $filter->filter('This contains no ending tag'); // returns "This contains" ``` ```php $filter = new Laminas\Filter\StripTags(['allowTags' => 'a']); $input = "A text with
a
link"; print $filter->filter($input); // returns "A text with a link" ``` ```php $filter = new Laminas\Filter\StripTags([ 'allowTags' => 'img', 'allowAttribs' => 'src', ]); $input = "A text with
a picture"; print $filter->filter($input); // returns "A text with a picture" ``` -------------------------------- ### Execute Filter Statically with Basic Usage - PHP Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/static-filter.md Demonstrates the basic static execution of a filter using StaticFilter::execute(). It takes the input data and the filter's base class name as arguments. The filter is automatically loaded, instantiated, and its filter() method is applied. ```php echo StaticFilter::execute('&', 'HtmlEntities'); ``` -------------------------------- ### Register Custom Filters with Filter Plugin Manager (Constructor) Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/plugin-manager.md Demonstrates registering custom filters and their factories, along with aliases, by passing a configuration array directly to the constructor of `LaminasFilterFilterPluginManager`. ```php $filterPluginManager = new Laminas\Filter\FilterPluginManager( new Laminas\ServiceManager\ServiceManager(), [ 'factories' => [ Album\Filter\ExampleFilter::class => Album\Filter\ExampleFilterFactory::class, ], 'aliases' => [ 'examplefilter' => Album\Filter\ExampleFilter::class, ], 'abstract_factories' => [], 'delegators' => [], // … ] ); ``` -------------------------------- ### Transform Camel Case to Dashed Lowercase String Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/inflector.md This example demonstrates how to use Laminas\Filter\Inflector to transform a camel-cased string into a dashed, lowercase format suitable for file paths or URLs. It utilizes the Word\CamelCaseToDash and StringToLower filters. ```php $pluginManager = $container->get(LaminasFilterFilterPluginManager::class); $inflector = new LaminasFilterInflector($pluginManager, [ 'target' => 'pages/:page.:suffix', 'rules' => [ ':page' => [ LaminasFilterWordCamelCaseToDash::class, LaminasFilterStringToLower::class, ], 'suffix' => 'html', ], ]); $filtered = $inflector->filter(['page' => 'camelCasedWords']); // pages/camel-cased-words.html $filtered = $inflector->filter(['page' => 'this_is_not_camel_cased']); // pages/this_is_not_camel_cased.html ``` -------------------------------- ### PHP: Create and Use ImmutableFilterChain Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/filter-chains.md Illustrates the creation and usage of Laminas' ImmutableFilterChain. It shows how to initialize the chain with filters and how attaching new filters returns a new instance, preserving the original chain's immutability. ```php $pluginManager = $container->get(Laminas\Filter\FilterPluginManager::class); $chain = new ImmutableFilterChain( $pluginManager, [ 'filters' => [ ['name' => StringTrim::class], ['name' => StringToLower::class], ], ] ); // attach and attachByName will return a new instance $chainRev = $chain->attach(static fn (string $value): string => strrev($value)); print $chain->filter(' OOF '); // 'oof' print $chainRev->filter(' OOF '); // 'foo' ``` -------------------------------- ### Callback Filter with Class Invoke Method Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/standard-filters.md Demonstrates using the __invoke method of a class as a callback for the Laminas\Filter\Callback filter, leveraging PHP 5.5's ::class resolution. ```php class MyClass { public function __invoke($param); } // The filter definition $filter = new Laminas\Filter\Callback(MyClass::class); print $filter->filter('Hello!'); ``` -------------------------------- ### Using Laminas Filters without StaticFilter (PHP) Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/migration/v2-to-v3.md Demonstrates how to achieve similar behavior to StaticFilter by directly instantiating and using filters. This method is suitable for filters with simple construction requirements. ```php $filtered = (new \Laminas\Filter\HtmlEntities())('Nuts & Bolts'); ``` -------------------------------- ### Allowing Specific Tags with Specific Attributes in PHP Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/standard-filters.md Illustrates advanced configuration of LaminasFilterStripTags to specify allowed attributes for particular allowed tags. This example allows 'img' tags with 'src' and 'width' attributes, and 'a' tags with 'href' attributes. ```php $filter = new Laminas\Filter\StripTags([ 'allowTags' => [ 'img' => [ 'src', 'width' ], 'a' => [ 'href' ] ] ]); $input = "A text with
a picture click " . "here!"; print $filter->filter($input); ``` -------------------------------- ### Using Laminas FilterPluginManager (PHP) Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/migration/v2-to-v3.md Shows how to retrieve and use filters via the FilterPluginManager, which is recommended for filters requiring more complex configuration or dependency injection. This approach leverages dependency injection for managing filter instances. ```php $pluginManager = $container->get(\Laminas\Filter\FilterPluginManager::class); $filter = $pluginManager->get(\Laminas\Filter\HtmlEntities::class); $filtered = $filter->filter('A String'); ``` -------------------------------- ### Verify Filter Non-Sharing Behavior in PHP Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/plugin-manager.md This code snippet illustrates that the Laminas filter plugin manager does not share filter instances. Each call to `get()` for the same filter class will return a new instance, as indicated by the inequality check. ```php $filterPluginManager->get(ExampleFilter::class) !== $filterPluginManager->get(ExampleFilter::class); ``` -------------------------------- ### Creating a Compressed Archive File Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/standard-filters.md Creates a compressed archive file (e.g., 'filename.bz2') by providing the archive name in the adapter's options. The content of an existing archive file will be overwritten. ```php $filter = new Laminas\Filter\Compress([ 'adapter' => 'Bz2', 'options' => [ 'archive' => 'filename.bz2', ], ]); $compressed = $filter->filter('Uncompressed string'); // Returns true on success, and creates the archive file ``` -------------------------------- ### Maintain Inflector Target via Class Member Reference Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/inflector.md Provides an example of how to link an Inflector's target to a class member variable using `setTargetReference()`. This ensures that any changes to the class member automatically update the Inflector's target. ```php class Foo { /** * @var string Inflector target */ protected $target = 'foo/:bar/:baz.:suffix'; /** * Constructor * @return void */ public function __construct() { $this->inflector = new Laminas\Filter\Inflector(); $this->inflector->setTargetReference($this->target); } /** * Set target; updates target in inflector * * @param string $target * @return Foo */ public function setTarget($target) { $this->target = $target; return $this; } } ``` -------------------------------- ### Using Laminas Filter as an Invokable (StringToLower) Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/basic-usage.md Demonstrates using a Laminas filter, specifically StringToLower, as an invokable object by leveraging the __invoke magic method. This allows direct calling of the filter instance with input data. ```php $strtolower = new Laminas\Filter\StringToLower; echo $strtolower('I LOVE Laminas!'); // i love laminas! $laminaslove = $strtolower('I LOVE Laminas!'); ``` -------------------------------- ### Callback Filter with Class Method Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/standard-filters.md Illustrates using a static method from a class as a callback for the Laminas\Filter\Callback filter. ```php class MyClass { public static function reverse($param); } // The filter definition $filter = new Laminas\Filter\Callback(array('MyClass', 'reverse')); print $filter->filter('Hello!'); ``` -------------------------------- ### Custom Filter Extending AbstractFilter (Laminas < v3) Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/migration/refactoring-from-abstract-filter.md This PHP code defines a custom filter by extending Laminas' `AbstractFilter`. It includes a filter method that returns configurable values based on a boolean input and methods for getting and setting these configurable options. ```php use Laminas\Filter\AbstractFilter; class MyFilter extends AbstractFilter { public function filter($value) { if (! is_bool($value)) { return $value; } return $value ? $this->getTrueValue() : $this->getFalseValue(); } public function getTrueValue() { return $this->options['true_value'] } public function getFalseValue() { return $this->options['false_value'] } public function setTrueValue(string $value) { $this->options['true_value'] = $value; } public function setFalseValue(string $value) { $this->options['false_value'] = $value; } } ``` -------------------------------- ### Implement Laminas FilterInterface Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/writing-filters.md Demonstrates creating a custom filter class by implementing `Laminas\Filter\FilterInterface`. This interface requires the `filter()` and `__invoke()` methods for performing value transformations. ```php namespace Application\Filter; use Laminas\Filter\FilterInterface; final class MyFilter implements FilterInterface { public function filter(mixed $value): mixed { // perform some transformation upon $value to arrive at $valueFiltered return $valueFiltered; } public function __invoke(mixed $value): mixed { return $this->filter($value); } } ``` -------------------------------- ### Configure Multiple Options for Different Source Files (PHP) Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/file.md Demonstrates configuring the Rename filter to handle multiple source files with distinct renaming rules, including target paths, overwriting behavior, and randomization. ```php $filter = new \Laminas\Filter\File\Rename([ [ 'source' => 'fileA.txt', 'target' => '/dest1/newfileA.txt', 'overwrite' => true, ], [ 'source' => 'fileB.txt', 'target' => '/dest2/newfileB.txt', 'randomize' => true, ], ]); echo $filter->filter('fileA.txt'); // File has been renamed to '/dest1/newfileA.txt' echo $filter->filter('fileB.txt'); // File has been renamed to '/dest2/newfileB_4b3403665fea6.txt' ``` -------------------------------- ### PHP: Configure Laminas Filter Chain with Array Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/filter-chains.md Demonstrates how to define a filter chain configuration array in PHP. This includes specifying filters by name, options, and priority, as well as defining callbacks and their priorities. ```php $filterChainConfig = [ 'filters' => [ [ 'name' => SomeFilter::class, // Required. Must be an alias or a FQCN registered in the plugin manager 'options' => [ /* ... */ ], // Optional. Provide options specific to the required filter 'priority' => 500, // Optional. Set the execution priority of the filter (Default 1000) ], ], 'callbacks' => [ [ 'callback' => static fn (string $in): string => strrev($in), // Required. Any type of PHP callable 'priority' => 500, // Optional priority, default 1000 ], [ 'callback' => new Laminas\Filter\StringToLower(), // Any object implementing FilterInterface ], ], ]; ``` -------------------------------- ### Compressing a String with Bz2 Adapter Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/standard-filters.md Initializes the Laminas Compress filter with the Bz2 adapter and compresses a given string. The filtered value is the compressed version of the original string. ```php $filter = new Laminas\Filter\Compress('Bz2'); $compressed = $filter->filter('Uncompressed string'); // Returns the compressed string ``` -------------------------------- ### Configure Multiple File Renaming Options with Laminas Filter Rename Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v3/file.md Demonstrates configuring different options for multiple source files using LaminasFilterFileRename. This allows for complex renaming and moving logic based on file patterns. ```php $filter = new \Laminas\Filter\File\Rename([ [ 'match' => '*.pdf' 'target_directory' => '/pdf-files/', 'rename_to' => 'newfileA.pdf', 'overwrite' => true, ], [ 'match' => '*.txt' 'target_directory' => '/text-files/', 'rename_to' => 'newfileB.txt', 'randomize' => true, ], ]); echo $filter->filter('fileA.txt'); // File has been renamed to '/dest1/newfileA.txt' echo $filter->filter('fileB.txt'); // File has been renamed to '/dest2/newfileB_4b3403665fea6.txt' ``` -------------------------------- ### StringToUpper Filter Usage Source: https://github.com/laminas/laminas-filter/blob/3.3.x/docs/book/v2/standard-filters.md Demonstrates the basic usage of the StringToUpper filter to convert a string to uppercase. It also shows how to specify encoding for different character sets, provided the mbstring extension is enabled. ```php $filter = new Laminas\Filter\StringToUpper(); print $filter->filter('Sample'); // returns "SAMPLE" ``` ```php $filter = new Laminas\Filter\StringToUpper(['encoding' => 'UTF-8']); // or do this afterwards $filter->setEncoding('ISO-8859-1'); ```