Next, we will consider the usage of the most important standard filters. These describe the methods (and options) a filter has and provide code examples showing how to instantiate the filter and apply it to input data. If you need to use a filter not covered in this section, please refer to Standard Filters section of the Zend Framework Reference Manual.
In this section, we will consider several filters from the group of filters related to casting input data to the specified type and provide their usage examples.
The ToInt
filter is a very simple filter that is designed to cast an arbitrary scalar
data to an integer. This filter may be useful when adding validation rules for
form fields that must contain an integer numeric values (e.g., a drop-down list or a
text field containing an amount of something).
The ToInt
class has the single filter()
method.
The
ToInt
filter will not cast a non-scalar value. If you pass it an array, it will return it as is.
Below, you can find a code example illustrating the usage of the ToInt
filter.
<?php
// Create ToInt filter.
$filter = new \Zend\Filter\ToInt();
// Filter a value casting it to an integer number.
$filteredValue = $filter->filter('10'); // Returns (int) 10.
$filteredValue2 = $filter->filter(['10', '20']); // Returns array as is.
In the code above, we pass the string "10" to the filter (line 6). The expected return value is the integer 10.
In line 7, we pass an array to the filter. Because the ToInt
filter works with scalar values only,
it returns the array as is (without changes) and raises a PHP warning.
The Boolean
class is a filter that is designed to cast an arbitrary data to a boolean value
(true
or false
). This filter can be used for filtering check box form fields.
Its public methods are listed in table 8.3.
Method name | Description |
---|---|
filter($value) |
Returns a boolean representation of $value . |
setCasting($flag) |
Sets casting flag. |
getCasting() |
Returns the casting flag. |
setType($type) |
Sets types from which to cast. |
getType() |
Returns types. |
setTranslations($translations) |
Sets translations. |
getTranslations() |
Returns the translations. |
The filter provides several methods allowing to set filtering options (setCasting()
, setType()
,
and setTranslations()
).
The setCasting()
method allows to choose one of two modes in which the filter may operate.
If the flag is true
, the filter will behave like the PHP (boolean)
cast operator. Otherwise
(if the flag is set to false
), it will cast only from types defined by the setType()
method, and
all other values will be returned as is.
The setType()
filter's method allows to define from which types to cast. This method accepts the
single argument $type
, which can be either an OR combination of TYPE_
-prefixed constants or an
array containing the literal equivalents of the constants. Possible constants accepted by the
setType()
method and their literal equivalents are listed in table 8.4:
Constant | Numeric Value | Literal Equivalent | Description |
---|---|---|---|
TYPE_BOOLEAN |
1 | "boolean" | Returns a boolean value as is. |
TYPE_INTEGER |
2 | "integer" | Converts an integer 0 value to false . |
TYPE_FLOAT |
4 | "float" | Converts a float 0.0 value to false . |
TYPE_STRING |
8 | "string" | Converts an empty string '' to false . |
TYPE_ZERO_STRING |
16 | "zero" | Converts a string containing the single character zero ('0') to false . |
TYPE_EMPTY_ARRAY |
32 | "array" | Converts an empty array to false . |
TYPE_NULL |
64 | "null" | Converts a null value to false . |
TYPE_PHP |
127 | "php" | Converts values according to PHP when casting them to boolean. (This is the default behavior.) |
TYPE_FALSE_STRING |
128 | "false" | Converts a string containing the word "false" to a boolean false . |
TYPE_LOCALIZED |
256 | "localized" | Converts a localized string which contains certain word to boolean. |
TYPE_ALL |
511 | "all" | Converts all above types to boolean. |
The following code example shows two equivalent ways you can call the setType()
method:
<?php
use Zend\Filter\Boolean;
// Call the setType() and pass it a combination of constants.
$filter->setType(Boolean::TYPE_BOOLEAN|
Boolean::TYPE_INTEGER|
Boolean::TYPE_STRING);
// Call the setType() and pass it an array with literal equivalents.
$filter->setType(['boolean', 'integer', 'string']);
The setTranslations()
method allows to define localized equivalents of boolean true
and false
values. This method accepts a single parameter, which must be an array in the form of key=>value
pairs, where the key is a localized string and the value is its boolean representation. The
following code example shows how to use the setTranlsations()
method:
<?php
$filter->setTranslations([
'yes' => true, // English 'yes'
'no' => false, // English 'no'
'ja' => true, // German 'yes'
'nicht' => false, // German 'no'
'да' => true, // Russian 'yes'
'нет' => false // Russian 'no'
]);
Below, we provide a code example illustrating the usage of the Boolean
filter.
<?php
// Create ToBoolean filter.
$filter = new \Zend\Filter\Boolean();
// Optionally configure the filter.
$filter->setCasting(true);
$filter->setType(\Zend\Filter\Boolean::TYPE_ALL);
$filter->setTranslations(['yes'=>true, 'no'=>false]);
// Filter a value casting it to a boolean number.
$filteredValue = $filter->filter('false'); // Returns boolean false.
$filteredValue2 = $filter->filter('1'); // Returns boolean true.
$filteredValue3 = $filter->filter('false'); // Returns boolean false.
$filteredValue4 = $filter->filter('yes'); // Returns boolean true.
The ToNull
filter is designed to cast an arbitrary data to a null
value if it meets specific
criteria. This may be useful when you work with a database and want to have a null
value instead
of any other type. If the value cannot be treated as null
, the filter will return the value as is.
The ToNull
filter's public methods are listed in table 8.5.
Method name | Description |
---|---|
filter($value) |
Casts the $value to null , if possible; otherwise returns values as is. |
setType($type) |
Defines from which types to cast. |
getType() |
Returns defined types. |
By default, the ToNull
filter behaves like PHP's empty()
function: if the empty()
function
returns a boolean true
on the input data, then the filter will return the null
value on that
data, as well.
The setType()
method can be used to set the type from which the filter will cast to null
.
This method takes a single parameter, which can either be a combination of TYPE_
-prefixed
constants listed in table 8.6 or an array of their literal equivalents.
Constant | Numeric Value | Literal Equivalent | Description |
---|---|---|---|
TYPE_BOOLEAN |
1 | "boolean" | Converts a boolean false value to null . |
TYPE_INTEGER |
2 | "integer" | Converts an integer 0 value to null . |
TYPE_EMPTY_ARRAY |
4 | "array" | Converts an empty array to null . |
TYPE_STRING |
8 | "string" | Converts an empty string '' to null . |
TYPE_ZERO_STRING |
16 | "zero" | Converts a string containing the single character zero ('0') to null . |
TYPE_FLOAT |
32 | "float" | Converts a float 0.0 value to null . |
TYPE_ALL |
63 | "all" | Converts all above types to null . This is the default behavior. |
The following code example illustrates two equivalent ways you can call the setType()
method:
<?php
use Zend\Filter\ToNull;
// Call the setType() and pass it a combination of constants.
$filter->setType(ToNull::TYPE_ZERO_STRING|ToNull::TYPE_STRING);
// Call the setType() and pass it an array with literal equivalents.
$filter->setType(['zero', 'string']);
Below, a code example showing how to use the ToNull
filter is provided:
<?php
// Create ToNull filter.
$filter = new \Zend\Filter\ToNull();
// Optionally configure the filter.
$filter->setType(\Zend\Filter\ToNull::TYPE_ALL);
$filteredValue = $filter->filter('0'); // Returns null.
$filteredValue2 = $filter->filter('1'); // Returns string '1'.
$filteredValue3 = $filter->filter(false); // Returns null.
The DateTimeFormatter
filter accepts a date in an arbitrary format and converts it into
the desired format.
This filter can accept a string (e.g., '2014-03-22 15:36'), an integer timestamp (like the
time()
PHP function returns) or an instance of theDateTime
PHP class. TheDateTimeFormatter
filter may throw aZend\Filter\Exception\InvalidArgumentException
exception if you pass it a date in an incorrect format.
Filter's public methods are listed in table 8.7.
Method name | Description |
---|---|
__construct($options) |
Constructs the filter. |
filter($value) |
Transforms the date into the desired format. |
setFormat($format) |
Sets the date format. |
In the code example below, we show how to create the filter, pass it a string date, and convert it to the desired format:
<?php
// Create DateTimeFormatter filter.
$filter = new \Zend\Filter\DateTimeFormatter();
// Set filter's format (optional).
$filter->setFormat('F j, Y g:i A');
// Transform the date to the specified format.
$filteredValue = $filter->filter('2014-03-22 15:36');
// The expected output is 'March 22, 2014 3:36 PM'.
Internally, the
DateTimeFormatter
filter uses theDateTime
class from the PHP standard library for converting and formatting dates. For available date formats, please refer to the PHP documentation for theDateTime
class.
In this section, we will consider usage examples of the filters from the group of filters related to manipulating file paths.
The BaseName
filter class is just a wrapper on the basename()
PHP function.
It takes a string containing the path to a file or directory and returns the trailing
name component.
Below, you can find an example of the BaseName
filter usage:
<?php
// Create BaseName filter.
$filter = new \Zend\Filter\BaseName();
// Filter a file path and return its last part.
$filteredValue = $filter->filter('/var/log/httpd/error.log');
// The expected filter's output is the 'error.log'.
The
BaseName
filter will not process a non-scalar value. If you pass it an array, it will return the array as is and raise a PHP warning.
The Dir
filter class is just a wrapper on the dirname()
PHP function.
It takes a string containing the path to a file or directory and returns the parent
directory's path.
The
Dir
filter will not process a non-scalar value. If you pass it an array, it will return the array as is.
Below, a code example demonstrating the usage of the Dir
filter is provided.
<?php
// Create Dir filter.
$filter = new \Zend\Filter\Dir();
// Filter a file path and return its directory name part.
$filteredValue = $filter->filter('/var/log/httpd/error.log');
// The expected filter's output is the '/var/log/httpd'.
The RealPath
filter takes an absolute or a relative file path as a string input argument. It
expands all symbolic links and resolves references to '/./', '/../' and extra '/' characters
in the input path and returns the canonicalized absolute pathname.
The
RealPath
filter is a wrapper over therealpath()
PHP function.
Filter's public methods are listed in table 8.8.
Method name | Description |
---|---|
__construct($options) |
Constructs the filter. |
filter($value) |
Returns canonicalized absolute pathname. |
setExists($flag) |
Specifies if the path must exist for this filter to succeed. The value true means the path must exist; the value false means a nonexisting path can be given. |
getExists() |
Returns true if the filtered path must exist. |
The RealPath
filter returns a boolean false
on failure, e.g., if the file does not
exist. If a nonexisting path is allowed, you can call the setExists()
method with the
false
parameter.
Below, a code example demonstrating the usage of the RealPath
filter is provided.
<?php
// Create RealPath filter.
$filter = new \Zend\Filter\RealPath();
// Filter a file path (it is assumed that the current
// working directory is /var/log/httpd and that it contains
// the error.log file).
$filteredValue = $filter->filter('./error.log');
// The expected filter's output is the '/var/log/httpd/error.log'.
The
RealPath
filter will not process a non-scalar value. If you pass it an array, it will return the array as is.
In this section, we will consider several filters from the group of filters related to compressing and encrypting the input data. These filters are not very usable for filtering form data but can be used outside of forms with a great success.
The Compress
filter is designed to compress input data with some compression algorithm. For
example, you can use this filter to compress the data and save it as an archive file.
Filter's public methods are listed in table 8.9.
Method name | Description |
---|---|
__construct($options) |
Constructs the filter. |
filter($value) |
Performs data compression using the specified algorithm. |
getAdapter() |
Returns the current adapter, instantiating it if necessary. |
getAdapterName() |
Retrieves adapter name. |
setAdapter($adapter) |
Sets compression adapter. |
getAdapterOptions() |
Retrieves adapter options. |
setAdapterOptions($options) |
Sets adapter options. |
getOptions($option) |
Gets individual or all options from underlying adapter. |
The Compress
filter itself cannot compress data. Instead, it uses a so-called adapter class.
The adapter class must implement the CompressionAlgorithmInterface
interface. You attach an
adapter to the Compress
filter, and the adapter implements the concrete compression algorithm.
There are several standard adapter classes available (see figure 8.2 and table 8.10 below). Those
classes live in the Zend\Filter\Compress
namespace.
Class name | Description |
---|---|
Bz2 |
Bzip2 (Burrows–Wheeler) compression algorithm. |
Gz |
Gzip compression algorithm is based on the Deflate algorithm, which is a combination of LZ77 and Huffman coding. |
Zip |
ZIP is a compression algorithm widely used in Windows operating system. |
Tar |
Tarball file format is now commonly used to collect many files into one larger file for archiving while preserving file system information such as user and group permissions, dates, and directory structures. Widely used in Linux operating system. |
Lzf |
LZF is a very fast compression algorithm, ideal for saving space with only slight speed cost. |
Snappy |
Snappy is a fast data compression and decompression library developed by Google based on ideas from LZ77. |
Rar |
RAR is an archive file format that supports data compression, error recovery, and file spanning. |
Below, a code example demonstrating the usage of the Compress
filter is provided.
<?php
// Create Compress filter.
$filter = new \Zend\Filter\Compress();
// Configure the adapter.
$filter->setAdapter('Zip');
$filter->setAdapterOptions([
'archive' => 'example.zip',
]);
// Compress an input data (it is assumed that you have the testfile.txt
// file in the current working directory.
$filter->filter('testfile.txt');
In the code above, we create the instance of the Compress
filter (line 3), set its adapter
(line 6), set adapter's options (line 7), and finally, compress the input file (line 13). The
expected result, the example.zip archive file, will be created in the current directory. The
archive will contain the testfile.txt file.
The
Decompress
filter is a "mirror reflection" of theCompress
filter and can be used by analogy. By that reason, we do not cover theDecompress
filter in this section.
The Encrypt
filter's purpose is encrypting the input data with the specified algorithm.
Filter's public methods are listed in table 8.11.
Method name | Description |
---|---|
__construct($options) |
Constructs the filter. |
filter($value) |
Performs data encrypting using the specified algorithm. |
getAdapter() |
Returns the current adapter, instantiating it if necessary. |
setAdapter($adapter) |
Sets encrypting adapter. |
The Encrypt
filter uses adapter classes to perform actual data encryption. You attach an
adapter to the Encrypt
filter with the setAdapter()
method, and the adapter performs the
concrete encryption. An adapter class must implement the EncryptionAlgorithmInterface
interface.
There are several standard adapter classes available (see figure 8.3 below). Those
classes live in the Zend\Filter\Encrypt
namespace.
BlockCipher
-- implements symmetric block cipher algorithm.Openssl
-- uses an encryption algorithm from the OpenSSL library.Below, a code example demonstrating the usage of the Encrypt
filter is provided.
<?php
// Create Encrypt filter.
$filter = new \Zend\Filter\Encrypt();
// Set encryption adapter.
$filter->setAdapter('BlockCipher');
// Encrypt an input data.
$filteredValue = $filter->filter('some data to encrypt');
The expected result is a string encrypted with the block cipher.
The
Decrypt
filter is a "mirror reflection" of theEncrypt
filter and can be used by analogy. By that reason, we do not cover theDecrypt
filter in this section.
In this section, we will consider usage examples of the filters from the group of filters related to manipulating string data.
The StringToLower
filter class is designed for converting the input string data to lowercase
letters. The public methods of the filter are provided in table 8.12 below.
Method name | Description |
---|---|
__construct($options) |
Constructs the filter. |
filter($value) |
Converts the string to lowercase letters. |
setEncoding($encoding) |
Sets the input encoding for the given string. |
getEncoding() |
Returns the encoding. |
By default, the filter behaves like the strtolower()
PHP function. Given a string, it returns
the string with all alphabetic characters converted to lowercase. The "alphabetic characters" are
determined by the system locale. This means that in, for example, the default "C" locale,
characters such as umlaut-A (Ä) will not be converted.
Calling the setEncoding()
method on the filter and passing it an encoding to use forces this
filter to behave like the mb_strtolower()
PHP function. By contrast to strtolower()
, "alphabetic"
is determined by the Unicode character properties. Thus, the behavior of this function is not affected
by locale settings, and it can convert any characters that have 'alphabetic' property, such as A-umlaut (Ä).
If the value provided is non-scalar, the value will remain unfiltered, and an
E_USER_WARNING
will be raised indicating it cannot be filtered.
Below, a code example showing how to use the StringToLower
filter is provided:
<?php
// Create StringToLower filter.
$filter = new \Zend\Filter\StringToLower();
// (Optionally) set encoding on the filter.
$filter->setEncoding('UTF-8');
// Filter a string.
$filteredValue = $filter->filter('How to Start a Business in 10 Days');
// The expected filter's output is the 'how to start a business in 10 days'.
The
StringToUpper
filter (converting a string to uppercase letters) is a "mirror reflection" of theStringToLower
filter and can be used by analogy. By that reason, we do not cover theStringToUpper
filter in this section.
The PregReplace
filter can be used for performing a regular expression search and replace in a string data.
This filter is a wrapper over the preg_replace()
PHP function. The public methods of the filter are provided in table 8.13 below.
Method name | Description |
---|---|
__construct($options) |
Constructs the filter. |
filter($value) |
Performs a regular expression search and replace. |
setPattern($pattern) |
Sets the pattern to search for. It can be either a string or an array with strings. |
getPattern() |
Returns the pattern. |
setReplacement($replacement) |
Sets the string or an array with strings to replace. |
getReplacement() |
Gets currently set replacement value. |
Below, a code example showing how to use the PregReplace
filter is provided:
<?php
// Create PregReplace filter.
$filter = new \Zend\Filter\PregReplace();
// Configure the filter.
$filter->setPattern("/\s\s+/");
$filter->setReplacement(' ');
// Filter a string.
$filteredValue = $filter->filter('An example with multiple spaces.');
// The expected filter's output is the 'An example with multiple spaces.'
The StripTags
filter removes all tags (e.g. <!-- -->
, <p>
, <h1>
or <?php ?>
) from the input string.
It allows to explicitly define the tags which should not be stripped out. Additionally,
it provides an ability to specify which attributes are allowed across all allowed tags and/or specific tags only.
Public methods of the StripTags
filter are listed in table 8.14.
Method name | Description |
---|---|
__construct($options) |
Constructs the filter. |
filter($value) |
Returns the value with tags stripped off it. |
getAttributesAllowed() |
Returns the list of attributes allowed for the tags. |
setAttributesAllowed($attributesAllowed) |
Sets the list of attributes allowed for the tags. |
getTagsAllowed() |
Returns the list of tags allowed. |
setTagsAllowed($tagsAllowed) |
Sets the list of tags allowed. |
Below, a code example showing how to use the StripTags
filter is provided:
<?php
// Create StripTags filter.
$filter = new \Zend\Filter\StripTags();
// Configure the filter.
$filter->setTagsAllowed(['p']);
// Filter a string.
$filteredValue = $filter->filter(
'<p>Please click the following <a href="example.com">link</a>.</p>');
// The expected filter's output is the
// '<p>Please click the following link.</p>;'
The
StripTags
will not process a non-scalar value. If the value passed to the filter is non-scalar, the value will remain unfiltered.
The StripNewlines
filter is a very simple filter which returns the input string
without any newline control characters ("\r", "\n").
Below, a code example showing how to use the StripNewlines
filter is provided:
<?php
// Create StripNewlines filter.
$filter = new \Zend\Filter\StripNewlines();
// Filter a string.
$filteredValue = $filter->filter("A multi line\r\n string");
// The expected filter's output is the 'A multi line string'.
The
StripNewlines
will not process a non-scalar value. If the value passed to the filter is non-scalar, the value will remain unfiltered.
The UriNormalize
filter can be used for normalizing a URL string and (optionally) applying
a scheme part to it. The public methods of the filter are provided in table 8.15 below.
Method name | Description |
---|---|
filter($value) |
Filter the URL by normalizing it and applying a default scheme if set. |
setDefaultScheme($defaultScheme) |
Set the default scheme to use when parsing schemeless URIs. |
setEnforcedScheme($enforcedScheme) |
Set a URI scheme to enforce on schemeless URIs. |
The URL normalization procedure typically consists of the following steps:
The URL normalization procedure rules may be different for different protocols (schemes). If the URL doesn't contain
the scheme part, the http
scheme is assumed by default. You may use the UriNormalize
filter's setDefaultScheme()
method
to set the default scheme for URL normalization. It accepts any of the following schemes: http
, https
, file
, mailto
,
urn
, and tag
.
Additionally, the UriNormalize
filter's setEnforcedScheme()
allows to override the default scheme
part by the so-called "enforced scheme", if the original URL doesn't contain scheme part.
Below, a code example showing how to use the UriNormalize
filter is provided:
<?php
// Create UriNormalize filter.
$filter = new \Zend\Filter\UriNormalize();
// Configure the filter.
$filter->setDefaultScheme('http');
$filter->setEnforcedScheme('https');
// Filter an URL string.
$filteredValue = $filter->filter('www.example.com');
// The expected filter's output is the 'https://www.example.com/'.
Filters can be organized in a sequence. This is accomplished by the FilterChain
class. When
such a compound filter is run, the value filtered by the first filter is passed as an input for
the second one, and then the value filtered by the second filter will be passed to the third one,
and so on.
The
FilterChain
class is internally used by theInputFilter
container class for storing the sequence of filters attached to the form model's field.
Public methods provided by the FilterChain
class are presented in table 8.16:
Method name | Description |
---|---|
filter($value) |
Returns value filtered through each filter in the chain. Filters are run in the order in which they were added to the chain (FIFO). |
setOptions($options) |
Sets options. |
attach($callback, $priority) |
Attaches an existing filter instance (or a callback function) to the chain. |
attachByName($name, $options, $priority) |
Instantiates the filter by class name or alias and inserts it into the chain. |
merge($filterChain) |
Merges the filter chain with another filter chain. |
getFilters() |
Returns all the attached filters. |
count() |
Returns the count of attached filters. |
An example filter chain is shown in figure 8.4. It consists of the StringTrim
filter followed by
the StripTags
filter, which is then followed by the StripNewlines
filter.
To construct the filter chain like in figure 8.4, we can use the following code:
<?php
use Zend\Filter\FilterChain;
// Instantiate the filter chain.
$filter = new FilterChain();
// Insert filters into filter chain.
$filter->setOptions([
'filters'=>[
[
'name'=>'StringTrim',
'options'=>['charlist'=>"\r\n\t "],
'priority'=>FilterChain::DEFAULT_PRIORITY
],
[
'name'=>'StripTags',
'options'=>['tagsallowed'=>['p']],
'priority'=>FilterChain::DEFAULT_PRIORITY
],
[
'name'=>'StripNewlines',
'priority'=>FilterChain::DEFAULT_PRIORITY
]
]
]);
// Execute all filters in the chain.
$filteredValue = $filter->filter(" name@example.com<html>\n ");
// The expected output is 'name@example.com'.
In the code above, we instantiate the FilterChain
filter with the new
operator (line 5). In
line 8, we set construct the chain of filters with the setOptions()
method.
The method takes an array configuration which looks the same way as in InputFilter
's add()
method.
The array has "filters" key where you register the filters you want to insert into the chain. For each attached
filter, you provide the following subkeys:
StringTrim::class
) or its short alias (e.g., "StringTrim");DEFAULT_PRIORITY
.Finally, in line 28, we call the filter()
method, which walks through the chain and passes the filtered
value to each filter in turn.
Standard filters are designed to be used in frequently appearing situations. For example, you may
often need to trim a string or convert it to lowercase. However, sometimes there are cases
where you cannot use a standard filter. Here, the Callback
filter will be handy.
The Callback
filter is designed as a wrapper for your custom filtering algorithm. For example, this may
be useful when a standard filter is not suitable, and you need to apply your own filtering
algorithm to the data.
You implement your custom filtering algorithm as a callback function or a callback class method. A callback is a function or a public method of a class which is called by the
Callback
filter and is passed the value to be filtered and, optionally, user-defined argument(s).
The public methods provided by the Callback
filter are listed in table 8.17.
Method name | Description |
---|---|
filter($value) |
Executes a callback function as a filter. |
setCallback($callback) |
Sets a new callback for this filter. |
getCallback() |
Returns callback set for the filter. |
setCallbackParams($params) |
Sets parameters for the callback. |
getCallbackParams() |
Gets parameters for the callback. |
As you can see from the table, the Callback
filter provides the setCallback()
and setCallbackParams()
methods that can be used to set the callback function (or the callback class method) and,
optionally, pass it one or several parameters.
To demonstrate the usage of the Callback
filter, let's add the phone number field
to our ContactForm
form model class and attach a custom filter to it.
An international phone number typically looks like "1 (808) 456-7890". It consists of the country code followed by the three-digit area code enclosed into braces. The rest of the phone consists of the seven-digit subscriber code divided in two groups separated by a dash. The country code, the area code, and the subscriber code are separated by the space character. We will refer to this phone format as the "international" format.
The international phone format is required for making telephone calls between different countries (or areas). If the calls are made within the same area, the telephone number may simply look like "456-7890" (we just omit the country code and area code). We will refer to this phone format as the "local" phone format.
To make our filter as generic as possible, we assume that the user is required to enter the phone in international format for some forms and in local format for other forms. Because some site visitors may enter their phone number in a format different from what is required, we want to apply the filter that will "normalize" the phone number for us.
To do the phone "normalization", the filter will:
Because ZF3 does not provide a standard filter for accomplishing such phone filtering operation,
we will use the Callback
wrapper filter. To do that, we will make the following
changes to the code of our ContactForm
class:
<?php
// ...
class ContactForm extends Form
{
// ...
protected function addElements()
{
// ...
// Add "phone" field
$this->add([
'type' => 'text',
'name' => 'phone',
'attributes' => [
'id' => 'phone'
],
'options' => [
'label' => 'Your Phone',
],
]);
}
private function addInputFilter()
{
// ...
$inputFilter->add([
'name' => 'phone',
'required' => true,
'filters' => [
[
'name' => 'Callback',
'options' => [
'callback' => [$this, 'filterPhone'],
'callbackParams' => [
'format' => 'intl'
]
]
],
],
]);
}
// Custom filter for a phone number.
public function filterPhone($value, $format)
{
if(!is_scalar($value)) {
// Return non-scalar value unfiltered.
return $value;
}
$value = (string)$value;
if(strlen($value)==0) {
// Return empty value unfiltered.
return $value;
}
// First, remove any non-digit character.
$digits = preg_replace('#[^0-9]#', '', $value);
if($format == 'intl') {
// Pad with zeros if the number of digits is incorrect.
$digits = str_pad($digits, 11, "0", STR_PAD_LEFT);
// Add the braces, the spaces, and the dash.
$phoneNumber = substr($digits, 0, 1) . ' ('.
substr($digits, 1, 3) . ') ' .
substr($digits, 4, 3) . '-'.
substr($digits, 7, 4);
} else { // 'local'
// Pad with zeros if the number of digits is incorrect.
$digits = str_pad($digits, 7, "0", STR_PAD_LEFT);
// Add the dash.
$phoneNumber = substr($digits, 0, 3) . '-'. substr($digits, 3, 4);
}
return $phoneNumber;
}
}
In lines 11-20 of the code above, we add the "phone" field to the ContactForm
form model. The field
is a usual text input field, and we already had some experience of working with such fields earlier.
Then, in lines 26-40, we add a validation rule for the "phone" field of our form. Under the "filters"
key (line 29), we register the Callback
filter (here, we use the short alias Callback
, but you
can alternatively use the fully qualified class name Callback::class
).
The filter takes two options (line 32): the "callback" option and the "callback_params" option.
The "callback" option is an array consisting of two elements, which represent the class and the method to call, respectively. In this
example, the callback is the filterPhone()
method of the ContactForm
class. We pass the "format" parameter
to the callback method with the help of "callbackParams" option (line 34).
In lines 44-79, we define the filterPhone()
callback method, which takes two arguments:
the $value
is the phone number to filter, and the $format
is the desired phone number format.
The $format
parameter may either be 'local' (for local format) or 'intl' (for international format).
In the filterPhone()
callback method, we do the following:
First, in line 46, we check if the $value
parameter is a scalar and not an array. If the value
is not a scalar, we return it without change.
In line 53, we check the input value's length. We do nothing if the user entered an empty phone number; we just return it as is.
Then, we remove any non-digit characters (line 59).
If phone length is too short, we pad it with zeroes.
We add the braces, the dash, and the spaces for international phone numbers; or just the dash for local phone numbers.
Finally, we return the resulting phone number.
To see how this filter works, you can open the "http://localhost/contactus" URL in your web browser. If you enter some phone number in an incorrect format, the filter will fix the phone number and transform it to the desired format.