Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laminas Filter Laravel Package

laminas/laminas-filter

A collection of reusable data filters for PHP apps. Provides string and numeric normalization, file and HTML filters, and a plugin manager to compose filter chains. Useful for sanitizing and transforming input consistently across Laminas and other frameworks.

View on GitHub
Deep Wiki
Context7

Standard Filters

laminas-filter comes with a standard set of filters, available for immediate use.

AllowList

TIP: New Feature Available since version 2.12.0

Previously known as Whitelist. This filter will return null if the value being filtered is not present the filter's allowed list of values. If the value is present, it will return that value.

For the opposite functionality see the DenyList filter.

Supported Options

The following options are supported for Laminas\Filter\AllowList:

  • strict: Uses strict mode for comparisons; passed to in_array()'s third argument.
  • list: An array of allowed values.

Basic Usage

$allowList = new \Laminas\Filter\AllowList([
    'list' => ['allowed-1', 'allowed-2']
]);
echo $allowList->filter('allowed-2');   // => 'allowed-2'
echo $allowList->filter('not-allowed'); // => null

Alnum

The Alnum filter can be used to return only alphabetic characters and digits in the unicode "letter" and "number" categories, respectively. All other characters are suppressed.

This filter is part of the laminas-i18n package; you will need to include that package in your application to use it.

Supported Options

The following options are supported for Alnum:

Alnum([ boolean $allowWhiteSpace [, string $locale ]])
  • $allowWhiteSpace: If set to true, then whitespace characters are allowed. Otherwise they are suppressed. Default is false (whitespace is not allowed). Methods for getting/setting the allowWhiteSpace option are also available: getAllowWhiteSpace() and setAllowWhiteSpace().

  • $locale: The locale string used in identifying the characters to filter (locale name, e.g.en_US). If unset, it will use the default locale (Locale::getDefault()). Methods for getting/setting the locale are also available: getLocale() and setLocale().

Basic Usage

// Default settings, deny whitespace
$filter = new \Laminas\I18n\Filter\Alnum();
echo $filter->filter('This is (my) content: 123');
// Returns 'Thisismycontent123'

// First param in constructor is $allowWhiteSpace
$filter = new \Laminas\I18n\Filter\Alnum(true);
echo $filter->filter('This is (my) content: 123');
// Returns 'This is my content 123'

Supported Languages

Alnum works on almost all languages, except: Chinese, Japanese and Korean. Within these languages, the english alphabet is used instead of the characters from these languages. The language itself is detected using the Locale class.

Alpha

The Alpha filter can be used to return only alphabetic characters in the unicode "letter" category. All other characters are suppressed.

This filter is part of the laminas-i18n package; you will need to include that package in your application to use it.

Supported Options

The following options are supported for Alpha:

Alpha([ boolean $allowWhiteSpace [, string $locale ]])
  • $allowWhiteSpace: If set to true then whitespace characters are allowed. Otherwise they are suppressed. Default is false (whitespace is not allowed). Methods for getting/setting the allowWhiteSpace option are also available: getAllowWhiteSpace() and setAllowWhiteSpace().

  • $locale: The locale string used in identifying the characters to filter (locale name, e.g. en_US). If unset, it will use the default locale (Locale::getDefault()). Methods for getting/setting the locale are also available: getLocale() and setLocale().

Basic Usage

// Default settings, deny whitespace
$filter = new \Laminas\I18n\Filter\Alpha();
echo $filter->filter('This is (my) content: 123');
// Returns 'Thisismycontent'

// Allow whitespace
$filter = new \Laminas\I18n\Filter\Alpha(true);
echo $filter->filter('This is (my) content: 123');
// Returns 'This is my content '

Supported Languages

Alpha works on almost all languages, except: Chinese, Japanese and Korean. Within these languages, the english alphabet is used instead of the characters from these languages. The language itself is detected using the Locale class.

BaseName

Laminas\Filter\BaseName allows you to filter a string which contains the path to a file, and it will return the base name of this file.

Supported Options

There are no additional options for Laminas\Filter\BaseName.

Basic Usage

$filter = new Laminas\Filter\BaseName();

print $filter->filter('/vol/tmp/filename');

This will return 'filename'.

$filter = new Laminas\Filter\BaseName();

print $filter->filter('/vol/tmp/filename.txt');

This will return 'filename.txt'.

Blacklist

CAUTION: Deprecated This filter is deprecated since version 2.12.0. Use the DenyList filter instead.

Boolean

This filter changes a given input to be a BOOLEAN value. This is often useful when working with databases or when processing form values.

Supported Options

The following options are supported for Laminas\Filter\Boolean:

  • casting: When this option is set to TRUE, then any given input will be cast to boolean. This option defaults to TRUE.
  • translations: This option sets the translations which will be used to detect localized input.
  • type: The type option sets the boolean type which should be used. Read the following for details.

Default Behavior

By default, this filter works by casting the input to a BOOLEAN value; in other words, it operates in a similar fashion to calling (boolean) $value.

$filter = new Laminas\Filter\Boolean();
$value  = '';
$result = $filter->filter($value);
// returns false

This means that without providing any configuration, Laminas\Filter\Boolean accepts all input types and returns a BOOLEAN just as you would get by type casting to BOOLEAN.

Changing the Default Behavior

Sometimes, casting with (boolean) will not suffice. Laminas\Filter\Boolean allows you to configure specific types to convert, as well as which to omit.

The following types can be handled (in this precedence order):

  • localized: Converts any string as mapped (case sensitive) in the translations option.
  • false: Converts a string equal to the word "false" (case insensitive) to boolean FALSE.
  • null: Converts a NULL value to FALSE.
  • array: Converts an empty array to FALSE.
  • zero: Converts a string to FALSE if it equates to '0' after type juggling.
  • string: Converts an empty string '' to FALSE.
  • float: Converts a float 0.0 value to FALSE.
  • integer: Converts an integer 0 value to FALSE.
  • boolean: Returns a boolean value as is.

There are 2 additional special types:

  • all: Converts all above types to BOOLEAN. The same as setting all above types.
  • php: Converts all above types to BOOLEAN except localized or false. The same as setting all above types except localized or false.

All other given values will return TRUE by default.

There are several ways to select which of the above types are filtered. You can give one or multiple types and add them, you can give an array, you can use constants, or you can give a textual string. See the following examples:

// converts 0 to false
$filter = new Laminas\Filter\Boolean(Laminas\Filter\Boolean::TYPE_INTEGER);

// converts 0 and '0' to false
$filter = new Laminas\Filter\Boolean(
    Laminas\Filter\Boolean::TYPE_INTEGER + Laminas\Filter\Boolean::TYPE_ZERO_STRING
);

// converts 0 and '0' to false
$filter = new Laminas\Filter\Boolean([
    'type' => [
        Laminas\Filter\Boolean::TYPE_INTEGER,
        Laminas\Filter\Boolean::TYPE_ZERO_STRING,
    ],
]);

// converts 0 and '0' to false
$filter = new Laminas\Filter\Boolean([
    'type' => [
        'integer',
        'zero',
    ],
]);

You can also give an instance of Laminas\Config\Config to set the desired types. To set types after instantiation, use the setType() method.

Localized Booleans

As mentioned previously, Laminas\Filter\Boolean can also recognise localized "yes" and "no" strings. This means that you can ask your customer in a form for "yes" or "no" within his native language and Laminas\Filter\Boolean will convert the response to the appropriate boolean value.

To set the translation and the corresponding value, you can use the translations option or the method setTranslations. The translations must be set for any values you wish to map to boolean values.

$filter = new Laminas\Filter\Boolean([
    'type'         => Laminas\Filter\Boolean::TYPE_LOCALIZED,
    'translations' => [
        'ja'   => true,
        'nein' => false,
        'yes'  => true,
        'no'   => false,
    ],
]);

// returns false
$result = $filter->filter('nein');

// returns true
$result = $filter->filter('yes');

Disable Casting

Sometimes it is necessary to recognise only TRUE or FALSE and return all other values without changes. Laminas\Filter\Boolean allows you to do this by setting the casting option to FALSE.

In this case Laminas\Filter\Boolean will work as described in the following table, which shows which values return TRUE or FALSE. All other given values are returned without change when casting is set to FALSE

Type Constant Type String True False
Laminas\Filter\Boolean::TYPE_BOOLEAN boolean TRUE FALSE
Laminas\Filter\Boolean::TYPE_EMPTY_ARRAY array []
Laminas\Filter\Boolean::TYPE_FALSE_STRING false 'true' (case insensitive) 'false' (case insensitive)
Laminas\Filter\Boolean::TYPE_FLOAT float 1.0 0.0
Laminas\Filter\Boolean::TYPE_INTEGER integer 1 0
Laminas\Filter\Boolean::TYPE_NULL null NULL
Laminas\Filter\Boolean::TYPE_STRING string ''
Laminas\Filter\Boolean::TYPE_ZERO_STRING zero '1' '0'

The following example shows the behavior when changing the casting option:

$filter = new Laminas\Filter\Boolean([
    'type'    => Laminas\Filter\Boolean::TYPE_ALL,
    'casting' => false,
]);

// returns false
$result = $filter->filter(0);

// returns true
$result = $filter->filter(1);

// returns the value
$result = $filter->filter(2);

Callback

This filter allows you to use own methods in conjunction with Laminas\Filter. You don't have to create a new filter when you already have a method which does the job.

Supported Options

The following options are supported for Laminas\Filter\Callback:

  • callback: This sets the callback which should be used.
  • callback_params: This property sets the options which are used when the callback is processed.

Basic Usage

The usage of this filter is quite simple. In this example, we want to create a filter which reverses a string:

$filter = new Laminas\Filter\Callback('strrev');

print $filter->filter('Hello!');
// returns "!olleH"

As you can see it's really simple to use a callback to define custom filters. It is also possible to use a method, which is defined within a class, by giving an array as the callback:

class MyClass
{
    public static function reverse($param);
}

// The filter definition
$filter = new Laminas\Filter\Callback(array('MyClass', 'reverse'));
print $filter->filter('Hello!');

As of PHP 5.5 you can use ::class resolution for given callback class:

class MyClass
{
    public function __invoke($param);
}

// The filter definition
$filter = new Laminas\Filter\Callback(MyClass::class);
print $filter->filter('Hello!');

To get the actual set callback use getCallback() and to set another callback use setCallback().

Possible Exceptions

You should note that defining a callback method which can not be called will raise an exception.

Default Parameters within a Callback

It is also possible to define default parameters, which are given to the called method as an array when the filter is executed. This array will be concatenated with the value which will be filtered.

$filter = new Laminas\Filter\Callback([
    'callback' => 'MyMethod',
    'options'  => ['key' => 'param1', 'key2' => 'param2']
]);
$filter->filter(['value' => 'Hello']);

Calling the above method definition manually would look like this:

$value = MyMethod('Hello', 'param1', 'param2');

Compress and Decompress

These two filters are capable of compressing and decompressing strings, files, and directories.

Supported Options

The following options are supported for Laminas\Filter\Compress and Laminas\Filter\Decompress:

  • adapter: The compression adapter which should be used. It defaults to Gz.
  • options: Additional options which are given to the adapter at initiation. Each adapter supports its own options.

Supported Compression Adapters

The following compression formats are supported by their own adapter:

  • Bz2
  • Gz
  • Tar
  • Zip
  • Lzf
  • Rar

Each compression format has different capabilities as described below. All compression filters may be used in approximately the same ways, and differ primarily in the options available and the type of compression they offer (both algorithmically as well as string vs. file vs. directory)

Generic Handling

To create a compression filter, you need to select the compression format you want to use. The following example takes the Bz2 adapter. Details for all other adapters are described after this section.

The two filters are basically identical, in that they utilize the same backends. Laminas\Filter\Compress should be used when you wish to compress items, and Laminas\Filter\Decompress should be used when you wish to decompress items.

For instance, if we want to compress a string, we have to initialize Laminas\Filter\Compress and indicate the desired adapter:

$filter = new Laminas\Filter\Compress('Bz2');

To use a different adapter, you simply specify it to the constructor.

You may also provide an array of options or a Traversable object. If you do, provide minimally the key "adapter", and then either the key "options" or "adapterOptions", both of which should be an array of options to provide to the adapter on instantiation.

$filter = new Laminas\Filter\Compress([
    'adapter' => 'Bz2',
    'options' => [
        'blocksize' => 8,
    ],
]);

Default compression Adapter

When no compression adapter is given, then the Gz adapter will be used.

Decompression is essentially the same usage; we simply use the Decompress filter instead:

$filter = new Laminas\Filter\Decompress('Bz2');

To get the compressed string, we have to give the original string. The filtered value is the compressed version of the original string.

$filter     = new Laminas\Filter\Compress('Bz2');
$compressed = $filter->filter('Uncompressed string');
// Returns the compressed string

Decompression works in reverse, accepting the compressed string, and returning the original:

$filter     = new Laminas\Filter\Decompress('Bz2');
$compressed = $filter->filter('Compressed string');
// Returns the original, uncompressed string

Note on String Compression

Not all adapters support string compression. Compression formats like Rar can only handle files and directories. For details, consult the section for the adapter you wish to use.

Creating an Archive

Creating an archive file works almost the same as compressing a string. However, in this case we need an additional parameter which holds the name of the archive we want to create.

$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

In the above example, the uncompressed string is compressed, and is then written into the given archive file.

Existing Archives will be overwritten

The content of any existing file will be overwritten when the given filename of the archive already exists.

When you want to compress a file, then you must give the name of the file with its path:

$filter = new Laminas\Filter\Compress([
    'adapter' => 'Bz2',
    'options' => [
        'archive' => 'filename.bz2'
    ],
]);
$compressed = $filter->filter('C:\temp\compressme.txt');
// Returns true on success and creates the archive file

You may also specify a directory instead of a filename. In this case the whole directory with all its files and subdirectories will be compressed into the archive:

$filter = new Laminas\Filter\Compress([
    'adapter' => 'Bz2',
    'options' => [
        'archive' => 'filename.bz2'
    ],
]);
$compressed = $filter->filter('C:\temp\somedir');
// Returns true on success and creates the archive file

Do not compress large or base Directories

You should never compress large or base directories like a complete partition. Compressing a complete partition is a very time consuming task which can lead to massive problems on your server when there is not enough space or your script takes too much time.

Decompressing an Archive

Decompressing an archive file works almost like compressing it. You must specify either the archive parameter, or give the filename of the archive when you decompress the file.

$filter = new Laminas\Filter\Decompress('Bz2');
$decompressed = $filter->filter('filename.bz2');
// Returns true on success and decompresses the archive file

Some adapters support decompressing the archive into another subdirectory. In this case you can set the target parameter:

$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

Directories to extract to must exist

When you want to decompress an archive into a directory, then the target directory must exist.

Bz2 Adapter

The Bz2 Adapter can compress and decompress:

  • Strings
  • Files
  • Directories

This adapter makes use of PHP's Bz2 extension.

To customize compression, this adapter supports the following options:

  • archive: This parameter sets the archive file which should be used or created.
  • blocksize: This parameter sets the blocksize to use. It can be from '0' to '9'. The default value is '4'.

All options can be set at instantiation or by using a related method; for example, the related methods for 'blocksize' are getBlocksize() and setBlocksize(). You can also use the setOptions() method, which accepts an array of all options.

Gz Adapter

The Gz Adapter can compress and decompress:

  • Strings
  • Files
  • Directories

This adapter makes use of PHP's Zlib extension.

To customize the compression this adapter supports the following options:

  • archive: This parameter sets the archive file which should be used or created.
  • level: This compression level to use. It can be from '0' to '9'. The default value is '9'.
  • mode: There are two supported modes. compress and deflate. The default value is compress.

All options can be set at initiation or by using a related method. For example, the related methods for level are getLevel() and setLevel(). You can also use the setOptions() method which accepts an array of all options.

Lzf Adapter

CAUTION: Deprecated This adapter is deprecated since version 2.28.0. and will be removed with version 3.0.0. Consider an alternative compression format such as gz or bz2.

The Lzf Adapter can compress and decompress:

  • Strings

Lzf supports only Strings

The Lzf adapter can not handle files and directories.

This adapter makes use of PHP's Lzf extension.

There are no options available to customize this adapter.

Rar Adapter

CAUTION: Deprecated This adapter is deprecated since version 2.28.0. and will be removed with version 3.0.0. Consider an alternative compression format such as gz or bz2.

The Rar Adapter can compress and decompress:

  • Files
  • Directories

Rar does not support Strings

The Rar Adapter can not handle strings.

This adapter makes use of PHP's Rar extension.

Rar Compression not supported

Due to restrictions with the Rar compression format, there is no compression available for free. When you want to compress files into a new Rar archive, you must provide a callback to the adapter that can invoke a Rar compression program.

To customize compression, this adapter supports the following options:

  • archive: This parameter sets the archive file which should be used or created.
  • callback: A callback which provides compression support to this adapter.
  • password: The password which has to be used for decompression.
  • target: The target where the decompressed files will be written to.

All options can be set at instantiation or by using a related method. For example, the related methods for target are getTarget() and setTarget(). You can also use the setOptions() method which accepts an array of all options.

Tar Adapter

The Tar Adapter can compress and decompress:

  • Files
  • Directories

Tar does not support Strings

The Tar Adapter can not handle strings.

T...

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai