update v1.0.7.9 R.C.

This is a Release Candidate. We are still testing.
This commit is contained in:
Sujit Prasad
2016-08-03 20:04:36 +05:30
parent 8b6b924d09
commit ffa56a43cb
3830 changed files with 181529 additions and 495353 deletions

View File

@@ -0,0 +1,266 @@
# Changelog
All notable changes to this project will be documented in this file, in reverse chronological order by release.
## 2.8.1 - 2016-06-23
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#92](https://github.com/zendframework/zend-validator/pull/92) adds message
templates to the `ExcludeMimeType` validator, to allow differentiating
validation error messages from the `MimeType` validator.
## 2.8.0 - 2016-05-16
### Added
- [#58](https://github.com/zendframework/zend-validator/pull/58) adds a new
`Uuid` validator, capable of validating if Versions 1-5 UUIDs are well-formed.
- [#64](https://github.com/zendframework/zend-validator/pull/64) ports
`Zend\ModuleManager\Feature\ValidatorProviderInterface` to
`Zend\Validator\ValidatorProviderInterface`, and updates the `Module::init()`
to typehint against the new interface instead of the one from
zend-modulemanager. Applications targeting zend-mvc v3 can start updating
their code to implement the new interface, or simply duck-type against it.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Nothing.
## 2.7.3 - 2016-05-16
### Added
- [#67](https://github.com/zendframework/zend-validator/pull/67) adds support
for Punycoded top-level domains in the `Hostname` validator.
- [#79](https://github.com/zendframework/zend-validator/pull/79) adds and
publishes the documentation to https://zendframework.github.io/zend-validator/
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Nothing.
## 2.7.2 - 2016-04-18
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#65](https://github.com/zendframework/zend-validator/pull/65) fixes the
`Module::init()` method to properly receive a `ModuleManager` instance, and
not expect a `ModuleEvent`.
## 2.7.1 - 2016-04-06
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- This release updates the TLD list to the latest version from the IANA.
## 2.7.0 - 2016-04-06
### Added
- [#63](https://github.com/zendframework/zend-validator/pull/63) exposes the
package as a ZF component and/or generic configuration provider, by adding the
following:
- `ValidatorPluginManagerFactory`, which can be consumed by container-interop /
zend-servicemanager to create and return a `ValidatorPluginManager` instance.
- `ConfigProvider`, which maps the service `ValidatorManager` to the above
factory.
- `Module`, which does the same as `ConfigProvider`, but specifically for
zend-mvc applications. It also provices a specification to
`Zend\ModuleManager\Listener\ServiceListener` to allow modules to provide
validator configuration.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- Nothing.
## 2.6.0 - 2016-02-17
### Added
- [#18](https://github.com/zendframework/zend-validator/pull/18) adds a `GpsPoint`
validator for validating GPS coordinates.
- [#47](https://github.com/zendframework/zend-validator/pull/47) adds two new
classes, `Zend\Validator\Isbn\Isbn10` and `Isbn13`; these classes are the
result of an extract class refactoring, and contain the logic specific to
calcualting the checksum for each ISBN style. `Zend\Validator\Isbn` now
instantiates the appropriate one and invokes it.
- [#46](https://github.com/zendframework/zend-validator/pull/46) updates
`Zend\Validator\Db\AbstractDb` to implement `Zend\Db\Adapter\AdapterAwareInterface`,
by composing `Zend\Db\Adapter\AdapterAwareTrait`.
### Deprecated
- Nothing.
### Removed
- [#55](https://github.com/zendframework/zend-validator/pull/55) removes some
checks for `safe_mode` within the `MimeType` validator, as `safe_mode` became
obsolete starting with PHP 5.4.
### Fixed
- [#45](https://github.com/zendframework/zend-validator/pull/45) fixes aliases
mapping the deprecated `Float` and `Int` validators to their `Is*` counterparts.
- [#49](https://github.com/zendframework/zend-validator/pull/49)
[#50](https://github.com/zendframework/zend-validator/pull/50), and
[#51](https://github.com/zendframework/zend-validator/pull/51) update the
code to be forwards-compatible with zend-servicemanager and zend-stdlib v3.
- [#56](https://github.com/zendframework/zend-validator/pull/56) fixes the regex
in the `Ip` validator to escape `.` characters used as IP delimiters.
## 2.5.4 - 2016-02-17
### Added
- Nothing.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#44](https://github.com/zendframework/zend-validator/pull/44) corrects the
grammar on the `NOT_GREATER_INCLUSIVE` validation error message.
- [#45](https://github.com/zendframework/zend-validator/pull/45) adds normalized
aliases for the i18n isfloat/isint validators.
- Updates the hostname validator regexes per the canonical service on which they
are based.
- [#52](https://github.com/zendframework/zend-validator/pull/52) updates the
`Barcode` validator to cast empty options passed to the constructor to an
empty array, fixing type mismatch errors.
- [#54](https://github.com/zendframework/zend-validator/pull/54) fixes the IP
address detection in the `Hostname` validator to ensure that IPv6 is detected
correctly.
- [#56](https://github.com/zendframework/zend-validator/pull/56) updates the
regexes used by the `IP` validator when comparing ipv4 addresses to ensure a
literal `.` is tested between network segments.
## 2.5.3 - 2015-09-03
### Added
- [#30](https://github.com/zendframework/zend-validator/pull/30) adds tooling to
ensure that the Hostname TLD list stays up-to-date as changes are pushed for
the repository.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#17](https://github.com/zendframework/zend-validator/pull/17) and
[#29](https://github.com/zendframework/zend-validator/pull/29) provide more
test coverage, and fix a number of edge cases, primarily in validator option
verifications.
- [#26](https://github.com/zendframework/zend-validator/pull/26) fixes tests for
`StaticValidator` such that they make correct assertions now. In doing so, we
determined that it was possible to pass an indexed array of options, which
could lead to unexpected results, often leading to false positives when
validating. To correct this situation, `StaticValidator::execute()` now raises
an `InvalidArgumentException` when an indexed array is detected for the
`$options` argument.
- [#35](https://github.com/zendframework/zend-validator/pull/35) modifies the
`NotEmpty` validator to no longer treat the float `0.0` as an empty value for
purposes of validation.
- [#25](https://github.com/zendframework/zend-validator/pull/25) fixes the
`Date` validator to check against `DateTimeImmutable` and not
`DateTimeInterface` (as PHP has restrictions currently on how the latter can
be used).
## 2.5.2 - 2015-07-16
### Added
- [#8](https://github.com/zendframework/zend-validator/pull/8) adds a "strict"
configuration option; when enabled (the default), the length of the address is
checked to ensure it follows the specification.
### Deprecated
- Nothing.
### Removed
- Nothing.
### Fixed
- [#8](https://github.com/zendframework/zend-validator/pull/8) fixes bad
behavior on the part of the `idn_to_utf8()` function, returning the original
address in the case that the function fails.
- [#11](https://github.com/zendframework/zend-validator/pull/11) fixes
`ValidatorChain::prependValidator()` so that it works on HHVM.
- [#12](https://github.com/zendframework/zend-validator/pull/12) adds "6772" to
the Maestro range of the `CreditCard` validator.

View File

@@ -0,0 +1,43 @@
# Contributor Code of Conduct
The Zend Framework project adheres to [The Code Manifesto](http://codemanifesto.com)
as its guidelines for contributor interactions.
## The Code Manifesto
We want to work in an ecosystem that empowers developers to reach their
potential — one that encourages growth and effective collaboration. A space that
is safe for all.
A space such as this benefits everyone that participates in it. It encourages
new developers to enter our field. It is through discussion and collaboration
that we grow, and through growth that we improve.
In the effort to create such a place, we hold to these values:
1. **Discrimination limits us.** This includes discrimination on the basis of
race, gender, sexual orientation, gender identity, age, nationality, technology
and any other arbitrary exclusion of a group of people.
2. **Boundaries honor us.** Your comfort levels are not everyones comfort
levels. Remember that, and if brought to your attention, heed it.
3. **We are our biggest assets.** None of us were born masters of our trade.
Each of us has been helped along the way. Return that favor, when and where
you can.
4. **We are resources for the future.** As an extension of #3, share what you
know. Make yourself a resource to help those that come after you.
5. **Respect defines us.** Treat others as you wish to be treated. Make your
discussions, criticisms and debates from a position of respectfulness. Ask
yourself, is it true? Is it necessary? Is it constructive? Anything less is
unacceptable.
6. **Reactions require grace.** Angry responses are valid, but abusive language
and vindictive actions are toxic. When something happens that offends you,
handle it assertively, but be respectful. Escalate reasonably, and try to
allow the offender an opportunity to explain themselves, and possibly correct
the issue.
7. **Opinions are just that: opinions.** Each and every one of us, due to our
background and upbringing, have varying opinions. The fact of the matter, is
that is perfectly acceptable. Remember this: if you respect your own
opinions, you should respect the opinions of others.
8. **To err is human.** You might not intend it, but mistakes do happen and
contribute to build experience. Tolerate honest mistakes, and don't hesitate
to apologize if you make one yourself.

View File

@@ -0,0 +1,234 @@
# CONTRIBUTING
## RESOURCES
If you wish to contribute to Zend Framework, please be sure to
read/subscribe to the following resources:
- [Coding Standards](https://github.com/zendframework/zf2/wiki/Coding-Standards)
- [Contributor's Guide](http://framework.zend.com/participate/contributor-guide)
- ZF Contributor's mailing list:
Archives: http://zend-framework-community.634137.n4.nabble.com/ZF-Contributor-f680267.html
Subscribe: zf-contributors-subscribe@lists.zend.com
- ZF Contributor's IRC channel:
#zftalk.dev on Freenode.net
If you are working on new features or refactoring [create a proposal](https://github.com/zendframework/zend-validator/issues/new).
## Reporting Potential Security Issues
If you have encountered a potential security vulnerability, please **DO NOT** report it on the public
issue tracker: send it to us at [zf-security@zend.com](mailto:zf-security@zend.com) instead.
We will work with you to verify the vulnerability and patch it as soon as possible.
When reporting issues, please provide the following information:
- Component(s) affected
- A description indicating how to reproduce the issue
- A summary of the security vulnerability and impact
We request that you contact us via the email address above and give the project
contributors a chance to resolve the vulnerability and issue a new release prior
to any public exposure; this helps protect users and provides them with a chance
to upgrade and/or update in order to protect their applications.
For sensitive email communications, please use [our PGP key](http://framework.zend.com/zf-security-pgp-key.asc).
## RUNNING TESTS
> ### Note: testing versions prior to 2.4
>
> This component originates with Zend Framework 2. During the lifetime of ZF2,
> testing infrastructure migrated from PHPUnit 3 to PHPUnit 4. In most cases, no
> changes were necessary. However, due to the migration, tests may not run on
> versions < 2.4. As such, you may need to change the PHPUnit dependency if
> attempting a fix on such a version.
To run tests:
- Clone the repository:
```console
$ git clone git@github.com:zendframework/zend-validator.git
$ cd
```
- Install dependencies via composer:
```console
$ curl -sS https://getcomposer.org/installer | php --
$ ./composer.phar install
```
If you don't have `curl` installed, you can also download `composer.phar` from https://getcomposer.org/
- Run the tests via `phpunit` and the provided PHPUnit config, like in this example:
```console
$ ./vendor/bin/phpunit
```
You can turn on conditional tests with the phpunit.xml file.
To do so:
- Copy `phpunit.xml.dist` file to `phpunit.xml`
- Edit `phpunit.xml` to enable any specific functionality you
want to test, as well as to provide test values to utilize.
## Running Coding Standards Checks
This component uses [php-cs-fixer](http://cs.sensiolabs.org/) for coding
standards checks, and provides configuration for our selected checks.
`php-cs-fixer` is installed by default via Composer.
To run checks only:
```console
$ ./vendor/bin/php-cs-fixer fix . -v --diff --dry-run --config-file=.php_cs
```
To have `php-cs-fixer` attempt to fix problems for you, omit the `--dry-run`
flag:
```console
$ ./vendor/bin/php-cs-fixer fix . -v --diff --config-file=.php_cs
```
If you allow php-cs-fixer to fix CS issues, please re-run the tests to ensure
they pass, and make sure you add and commit the changes after verification.
## Recommended Workflow for Contributions
Your first step is to establish a public repository from which we can
pull your work into the master repository. We recommend using
[GitHub](https://github.com), as that is where the component is already hosted.
1. Setup a [GitHub account](http://github.com/), if you haven't yet
2. Fork the repository (http://github.com/zendframework/zend-validator)
3. Clone the canonical repository locally and enter it.
```console
$ git clone git://github.com:zendframework/zend-validator.git
$ cd zend-validator
```
4. Add a remote to your fork; substitute your GitHub username in the command
below.
```console
$ git remote add {username} git@github.com:{username}/zend-validator.git
$ git fetch {username}
```
### Keeping Up-to-Date
Periodically, you should update your fork or personal repository to
match the canonical ZF repository. Assuming you have setup your local repository
per the instructions above, you can do the following:
```console
$ git checkout master
$ git fetch origin
$ git rebase origin/master
# OPTIONALLY, to keep your remote up-to-date -
$ git push {username} master:master
```
If you're tracking other branches -- for example, the "develop" branch, where
new feature development occurs -- you'll want to do the same operations for that
branch; simply substitute "develop" for "master".
### Working on a patch
We recommend you do each new feature or bugfix in a new branch. This simplifies
the task of code review as well as the task of merging your changes into the
canonical repository.
A typical workflow will then consist of the following:
1. Create a new local branch based off either your master or develop branch.
2. Switch to your new local branch. (This step can be combined with the
previous step with the use of `git checkout -b`.)
3. Do some work, commit, repeat as necessary.
4. Push the local branch to your remote repository.
5. Send a pull request.
The mechanics of this process are actually quite trivial. Below, we will
create a branch for fixing an issue in the tracker.
```console
$ git checkout -b hotfix/9295
Switched to a new branch 'hotfix/9295'
```
... do some work ...
```console
$ git commit
```
... write your log message ...
```console
$ git push {username} hotfix/9295:hotfix/9295
Counting objects: 38, done.
Delta compression using up to 2 threads.
Compression objects: 100% (18/18), done.
Writing objects: 100% (20/20), 8.19KiB, done.
Total 20 (delta 12), reused 0 (delta 0)
To ssh://git@github.com/{username}/zend-validator.git
b5583aa..4f51698 HEAD -> master
```
To send a pull request, you have two options.
If using GitHub, you can do the pull request from there. Navigate to
your repository, select the branch you just created, and then select the
"Pull Request" button in the upper right. Select the user/organization
"zendframework" as the recipient.
If using your own repository - or even if using GitHub - you can use `git
format-patch` to create a patchset for us to apply; in fact, this is
**recommended** for security-related patches. If you use `format-patch`, please
send the patches as attachments to:
- zf-devteam@zend.com for patches without security implications
- zf-security@zend.com for security patches
#### What branch to issue the pull request against?
Which branch should you issue a pull request against?
- For fixes against the stable release, issue the pull request against the
"master" branch.
- For new features, or fixes that introduce new elements to the public API (such
as new public methods or properties), issue the pull request against the
"develop" branch.
### Branch Cleanup
As you might imagine, if you are a frequent contributor, you'll start to
get a ton of branches both locally and on your remote.
Once you know that your changes have been accepted to the master
repository, we suggest doing some cleanup of these branches.
- Local branch cleanup
```console
$ git branch -d <branchname>
```
- Remote branch removal
```console
$ git push {username} :<branchname>
```
## Conduct
Please see our [CONDUCT.md](CONDUCT.md) to understand expected behavior when interacting with others in the project.

View File

@@ -0,0 +1,28 @@
Copyright (c) 2005-2015, Zend Technologies USA, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- Neither the name of Zend Technologies USA, Inc. nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

View File

@@ -0,0 +1,11 @@
# zend-validator
[![Build Status](https://secure.travis-ci.org/zendframework/zend-validator.svg?branch=master)](https://secure.travis-ci.org/zendframework/zend-validator)
[![Coverage Status](https://coveralls.io/repos/zendframework/zend-validator/badge.svg?branch=master)](https://coveralls.io/r/zendframework/zend-validator?branch=master)
zend-validator provides a set of commonly needed validators. It also provides a
simple validator chaining mechanism by which multiple validators may be applied
to a single datum in a user-defined order.
- File issues at https://github.com/zendframework/zend-validator/issues
- Documentation is at https://zendframework.github.io/zend-validator/

View File

@@ -0,0 +1,194 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
use Zend\Http\Client;
use Zend\Validator\Hostname;
require __DIR__ . '/../vendor/autoload.php';
define('IANA_URL', 'https://data.iana.org/TLD/tlds-alpha-by-domain.txt');
define('ZF2_HOSTNAME_VALIDATOR_FILE', __DIR__.'/../src/Hostname.php');
if (! file_exists(ZF2_HOSTNAME_VALIDATOR_FILE) || ! is_readable(ZF2_HOSTNAME_VALIDATOR_FILE)) {
printf("Error: cannont read file '%s'%s", ZF2_HOSTNAME_VALIDATOR_FILE, PHP_EOL);
exit(1);
}
if (! is_writable(ZF2_HOSTNAME_VALIDATOR_FILE)) {
printf("Error: Cannot update file '%s'%s", ZF2_HOSTNAME_VALIDATOR_FILE, PHP_EOL);
exit(1);
}
$newFileContent = []; // new file content
$insertDone = false; // becomes 'true' when we find start of $validTlds declaration
$insertFinish = false; // becomes 'true' when we find end of $validTlds declaration
$checkOnly = isset($argv[1]) ? $argv[1] === '--check-only' : false;
$response = getOfficialTLDs();
$ianaVersion = getVersionFromString('Version', strtok($response->getBody(), "\n"));
$validatorVersion = getVersionFromString('IanaVersion', file_get_contents(ZF2_HOSTNAME_VALIDATOR_FILE));
if ($checkOnly && $ianaVersion > $validatorVersion) {
printf(
'TLDs must be updated, please run `php bin/update_hostname_validator.php` and push your changes%s',
PHP_EOL
);
exit(1);
}
if ($checkOnly) {
printf('TLDs are up-to-date%s', PHP_EOL);
exit(0);
}
foreach (file(ZF2_HOSTNAME_VALIDATOR_FILE) as $line) {
// Replace old version number with new one
if (preg_match('/\*\s+IanaVersion\s+\d+/', $line, $matches)) {
$newFileContent[] = sprintf(" * IanaVersion %s\n", $ianaVersion);
continue;
}
if ($insertDone === $insertFinish) {
// Outside of $validTlds definition; keep line as-is
$newFileContent[] = $line;
}
if ($insertFinish) {
continue;
}
if ($insertDone) {
// Detect where the $validTlds declaration ends
if (preg_match('/^\s+\];\s*$/', $line)) {
$newFileContent[] = $line;
$insertFinish = true;
}
continue;
}
// Detect where the $validTlds declaration begins
if (preg_match('/^\s+protected\s+\$validTlds\s+=\s+\[\s*$/', $line)) {
$newFileContent = array_merge($newFileContent, getNewValidTlds($response->getBody()));
$insertDone = true;
}
}
if (! $insertDone) {
printf('Error: cannot find line with "protected $validTlds"%s', PHP_EOL);
exit(1);
}
if (!$insertFinish) {
printf('Error: cannot find end of $validTlds declaration%s', PHP_EOL);
exit(1);
}
if (false === @file_put_contents(ZF2_HOSTNAME_VALIDATOR_FILE, $newFileContent)) {
printf('Error: cannot write info file "%s"%s', ZF2_HOSTNAME_VALIDATOR_FILE, PHP_EOL);
exit(1);
}
printf('Validator TLD file updated.%s', PHP_EOL);
exit(0);
/**
* Get Official TLDs
*
* @return \Zend\Http\Response
* @throws Exception
*/
function getOfficialTLDs()
{
$client = new Client();
$client->setOptions([
'adapter' => 'Zend\Http\Client\Adapter\Curl',
]);
$client->setUri(IANA_URL);
$client->setMethod('GET');
$response = $client->send();
if (! $response->isSuccess()) {
throw new \Exception(sprintf("Error: cannot get '%s'%s", IANA_URL, PHP_EOL));
}
return $response;
}
/**
* Extract the first match of a string like
* "Version 2015072300" from the given string
*
* @param string $prefix
* @param string $string
* @return string
* @throws Exception
*/
function getVersionFromString($prefix, $string)
{
$matches = [];
if (! preg_match(sprintf('/%s\s+((\d+)?)/', $prefix), $string, $matches)) {
throw new Exception('Error: cannot get last update date');
}
return $matches[1];
}
/**
* Extract new Valid TLDs from a string containing one per line.
*
* @param string $string
* @return array
*/
function getNewValidTlds($string)
{
$decodePunycode = getPunycodeDecoder();
// Get new TLDs from the list previously fetched
$newValidTlds = [];
foreach (preg_grep('/^[^#]/', preg_split("#\r?\n#", $string)) as $line) {
$newValidTlds []= sprintf(
"%s'%s',\n",
str_repeat(' ', 8),
$decodePunycode(strtolower($line))
);
}
return $newValidTlds;
}
/**
* Retrieve and return a punycode decoder.
*
* TLDs are puny encoded.
*
* We need a decodePunycode function to translate TLDs to UTF-8:
*
* - use idn_to_utf8 if available
* - otherwise, use Hostname::decodePunycode()
*
* @return callable
*/
function getPunycodeDecoder()
{
if (function_exists('idn_to_utf8')) {
return 'idn_to_utf8';
}
$hostnameValidator = new Hostname();
$reflection = new ReflectionClass(get_class($hostnameValidator));
$decodePunyCode = $reflection->getMethod('decodePunycode');
$decodePunyCode->setAccessible(true);
return function ($encode) use ($hostnameValidator, $decodePunyCode) {
if (strpos($encode, 'xn--') === 0) {
return $decodePunyCode->invokeArgs($hostnameValidator, [substr($encode, 4)]);
}
return $encode;
};
}

View File

@@ -0,0 +1,61 @@
{
"name": "zendframework/zend-validator",
"description": "provides a set of commonly needed validators",
"license": "BSD-3-Clause",
"keywords": [
"zf2",
"validator"
],
"homepage": "https://github.com/zendframework/zend-validator",
"autoload": {
"psr-4": {
"Zend\\Validator\\": "src/"
}
},
"require": {
"php": "^5.5 || ^7.0",
"zendframework/zend-stdlib": "^2.7 || ^3.0",
"container-interop/container-interop": "^1.1"
},
"require-dev": {
"zendframework/zend-cache": "^2.6.1",
"zendframework/zend-config": "^2.6",
"zendframework/zend-db": "^2.7",
"zendframework/zend-filter": "^2.6",
"zendframework/zend-http": "^2.5.4",
"zendframework/zend-i18n": "^2.6",
"zendframework/zend-math": "^2.6",
"zendframework/zend-servicemanager": "^2.7.5 || ^3.0.3",
"zendframework/zend-session": "^2.6.2",
"zendframework/zend-uri": "^2.5",
"fabpot/php-cs-fixer": "1.7.*",
"phpunit/PHPUnit": "^4.0"
},
"suggest": {
"zendframework/zend-db": "Zend\\Db component",
"zendframework/zend-filter": "Zend\\Filter component, required by the Digits validator",
"zendframework/zend-i18n": "Zend\\I18n component to allow translation of validation error messages as well as to use the various Date validators",
"zendframework/zend-math": "Zend\\Math component",
"zendframework/zend-i18n-resources": "Translations of validator messages",
"zendframework/zend-servicemanager": "Zend\\ServiceManager component to allow using the ValidatorPluginManager and validator chains",
"zendframework/zend-session": "Zend\\Session component",
"zendframework/zend-uri": "Zend\\Uri component, required by the Uri and Sitemap\\Loc validators"
},
"minimum-stability": "dev",
"prefer-stable": true,
"extra": {
"branch-alias": {
"dev-master": "2.8-dev",
"dev-develop": "2.9-dev"
},
"zf": {
"component": "Zend\\Validator",
"config-provider": "Zend\\Validator\\ConfigProvider"
}
},
"autoload-dev": {
"psr-4": {
"ZendTest\\Validator\\": "test/"
}
}
}

View File

@@ -0,0 +1,12 @@
<div class="container">
<div class="jumbotron">
<h1>zend-validator</h1>
<p>
Validation classes for a wide range of domains, and the ability to chain validators to create complex validation criteria.
</p>
<pre><code class="language-bash">$ composer require zendframework/zend-validator</code></pre>
</div>
</div>

View File

@@ -0,0 +1 @@
../../README.md

View File

@@ -0,0 +1,213 @@
# Introduction
zend-validator provides a set of commonly needed validators. It also provides a
simple validator chaining mechanism by which multiple validators may be applied
to a single datum in a user-defined order.
## What is a validator?
A validator examines its input with respect to some requirements and produces a
boolean result indicating whether the input successfully validates against the
requirements. If the input does not meet the requirements, a validator may
additionally provide information about which requirement(s) the input does not
meet.
For example, a web application might require that a username be between six and
twelve characters in length, and may only contain alphanumeric characters. A
validator can be used for ensuring that a username meets these requirements. If
a chosen username does not meet one or both of the requirements, it would be
useful to know which of the requirements the username fails to meet.
## Basic usage of validators
Having defined validation in this way provides the foundation for
`Zend\Validator\ValidatorInterface`, which defines two methods, `isValid()` and
`getMessages()`. The `isValid()` method performs validation upon the provided
value, returning `true` if and only if the value passes against the validation
criteria.
If `isValid()` returns `false`, the `getMessages()` method will return an array
of messages explaining the reason(s) for validation failure. The array keys are
short strings that identify the reasons for validation failure, and the array
values are the corresponding human-readable string messages. The keys and values
are class-dependent; each validation class defines its own set of validation
failure messages and the unique keys that identify them. Each class also has a
`const` definition that matches each identifier for a validation failure cause.
> ### Stateful validators
>
> The `getMessages()` methods return validation failure information only for the
> most recent `isValid()` call. Each call to `isValid()` clears any messages and
> errors caused by a previous `isValid()` call, because it's likely that each
> call to `isValid()` is made for a different input value.
The following example illustrates validation of an e-mail address:
```php
use Zend\Validator\EmailAddress;
$validator = new EmailAddress();
if ($validator->isValid($email)) {
// email appears to be valid
} else {
// email is invalid; print the reasons
foreach ($validator->getMessages() as $messageId => $message) {
printf("Validation failure '%s': %s\n", $messageId, $message);
}
}
```
## Customizing messages
Validator classes provide a `setMessage()` method with which you can specify the
format of a message returned by `getMessages()` in case of validation failure.
The first argument of this method is a string containing the error message. You
can include tokens in this string which will be substituted with data relevant
to the validator. The token `%value%` is supported by all validators; this is
substituted with the value you passed to `isValid()`. Other tokens may be
supported on a case-by-case basis in each validation class. For example, `%max%`
is a token supported by `Zend\Validator\LessThan`. The `getMessageVariables()`
method returns an array of variable tokens supported by the validator.
The second optional argument is a string that identifies the validation failure
message template to be set, which is useful when a validation class defines more
than one cause for failure. If you omit the second argument, `setMessage()`
assumes the message you specify should be used for the first message template
declared in the validation class. Many validation classes only have one error
message template defined, so there is no need to specify which message template
you are changing.
```php
use Zend\Validator\StringLength;
$validator = new StringLength(8);
$validator->setMessage(
'The string \'%value%\' is too short; it must be at least %min% characters',
StringLength::TOO_SHORT
);
if (! $validator->isValid('word')) {
$messages = $validator->getMessages();
echo current($messages);
// "The string 'word' is too short; it must be at least 8 characters"
}
```
You can set multiple messages using the `setMessages()` method. Its argument is
an array containing key/message pairs.
```php
use Zend\Validator\StringLength;
$validator = new StringLength(['min' => 8, 'max' => 12]);
$validator->setMessages([
StringLength::TOO_SHORT => 'The string \'%value%\' is too short',
StringLength::TOO_LONG => 'The string \'%value%\' is too long',
]);
```
If your application requires even greater flexibility with which it reports
validation failures, you can access properties by the same name as the message
tokens supported by a given validation class. The `value` property is always
available in a validator; it is the value you specified as the argument of
`isValid()`. Other properties may be supported on a case-by-case basis in each
validation class.
```php
use Zend\Validator\StringLength;
$validator = new StringLength(['min' => 8, 'max' => 12]);
if (! $validator->isValid('word')) {
printf(
"Word failed: %s; its length is not between %d and %d\n",
$validator->value,
$validator->min,
$validator->max
);
}
```
## Translating messages
> ### Translation compatibility
>
> In versions 2.0 - 2.1, `Zend\Validator\AbstractValidator` implemented
> `Zend\I18n\Translator\TranslatorAwareInterface` and accepted instances of
> `Zend\I18n\Translator\Translator`. Starting in version 2.2.0, zend-validator
> now defines a translator interface, > `Zend\Validator\Translator\TranslatorInterface`,
> as well as it's own -aware variant, > `Zend\Validator\Translator\TranslatorAwareInterface`.
> This was done to reduce dependencies for the component, and follows the
> principal of Separated Interfaces.
>
> The upshot is that if you are migrating from a pre-2.2 version, and receiving
> errors indicating that the translator provided does not implement
> `Zend\Validator\Translator\TranslatorInterface`, you will need to make a
> change to your code.
>
> An implementation of `Zend\Validator\Translator\TranslatorInterface` is
> provided in `Zend\Mvc\I18n\Translator`, which also extends
> `Zend\I18n\Translator\Translator`. This version can be instantiated and used
> just as the original `Zend\I18n` version.
>
> A new service has also been registered with the MVC, `MvcTranslator`, which
> will return this specialized, bridge instance.
>
> Most users should see no issues, as `Zend\Validator\ValidatorPluginManager`
> has been modified to use the `MvcTranslator` service internally, which is how
> most developers were getting the translator instance into validators in the
> first place. You will only need to change code if you were manually injecting
> the instance previously.
Validator classes provide a `setTranslator()` method with which you can specify
an instance of `Zend\Validator\Translator\TranslatorInterface` which will
translate the messages in case of a validation failure. The `getTranslator()`
method returns the translator instance. `Zend\Mvc\I18n\Translator` provides an
implementation compatible with the validator component.
```php
use Zend\Mvc\I18n\Translator;
use Zend\Validator\StringLength;
$validator = new StringLength(['min' => 8, 'max' => 12]);
$translate = new Translator();
// configure the translator...
$validator->setTranslator($translate);
```
With the static `AbstractValidator::setDefaultTranslator()` method you can set a
instance of `Zend\Validator\Translator\TranslatorInterface` which will be used
for all validation classes, and can be retrieved with `getDefaultTranslator()`.
This prevents the need for setting a translator manually with each validator.
```php
use Zend\Mvc\I18n\Translator;
use Zend\Validator\AbstractValidator;
$translate = new Translator();
// configure the translator...
AbstractValidator::setDefaultTranslator($translate);
```
Sometimes it is necessary to disable the translator within a validator. To
achieve this you can use the `setDisableTranslator()` method, which accepts a
boolean parameter, and `isTranslatorDisabled()` to get the set value.
```php
use Zend\Validator\StringLength;
$validator = new StringLength(['min' => 8, 'max' => 12]);
if (! $validator->isTranslatorDisabled()) {
$validator->setDisableTranslator();
}
```
It is also possible to use a translator instead of setting own messages with
`setMessage()`. But doing so, you should keep in mind, that the translator works
also on messages you set your own.

View File

@@ -0,0 +1,108 @@
# Validation Messages
Each validator based on `Zend\Validator\ValidatorInterface` provides one or
multiple messages in the case of a failed validation. You can use this
information to set your own messages, or to translate existing messages which a
validator could return to something different.
Validation messages are defined as constant/template pairs, with the constant
representing a translation key. Such constants are defined per-class. Let's
look into `Zend\Validator\GreaterThan` for a descriptive example:
```php
protected $messageTemplates = [
self::NOT_GREATER => "'%value%' is not greater than '%min%'",
];
```
The constant `self::NOT_GREATER` refers to the failure and is used as the
message key, and the message template itself is used as the value within the
message array.
You can retrieve all message templates from a validator by using the
`getMessageTemplates()` method. It returns the above array containing all
messages a validator could return in the case of a failed validation.
```php
$validator = new Zend\Validator\GreaterThan();
$messages = $validator->getMessageTemplates();
```
Using the `setMessage()` method you can set another message to be returned in
case of the specified failure.
```php
use Zend\Validator\GreaterThan;
$validator = new GreaterThan();
$validator->setMessage('Please enter a lower value', GreaterThan::NOT_GREATER);
```
The second parameter defines the failure which will be overridden. When you omit
this parameter, then the given message will be set for all possible failures of
this validator.
## Using pre-translated validation messages
zend-validator is shipped with more than 45 different validators with more than
200 failure messages. It can be a tedious task to translate all of these
messages. For your convenience, pre-translated messages are provided in the
[zendframework/zend-i18n-resources](https://zendframework.github.io/zend-i18n-resources/)
package:
```bash
$ composer require zendframework/zend-i18n-resources
```
To translate all validation messages to German for example, attach a translator
to `Zend\Validator\AbstractValidator` using these resource files.
```php
use Zend\I18n\Translator\Resources;
use Zend\Mvc\I18n\Translator;
use Zend\Validator\AbstractValidator;
$translator = new Zend\Mvc\I18n\Translator();
$translator->addTranslationFilePattern(
'phpArray',
Resources::getBasePath(),
Resources::getPatternForValidator()
);
AbstractValidator::setDefaultTranslator($translator);
```
> ### Supported languages
>
> The supported languages may not be complete. New languages will be added with
> each release. Additionally feel free to use the existing resource files to
> make your own translations.
>
> You could also use these resource files to rewrite existing translations. So
> you are not in need to create these files manually yourself.
## Limit the size of a validation message
Sometimes it is necessary to limit the maximum size a validation message can
have; as an example, when your view allows a maximum size of 100 chars to be
rendered on one line. To enable this, `Zend\Validator\AbstractValidator`
is able to automatically limit the maximum returned size of a validation
message.
To get the actual set size use `Zend\Validator\AbstractValidator::getMessageLength()`.
If it is `-1`, then the returned message will not be truncated. This is default
behaviour.
To limit the returned message size, use `Zend\Validator\AbstractValidator::setMessageLength()`.
Set it to any integer size you need. When the returned message exceeds the set
size, then the message will be truncated and the string `**...**` will be added
instead of the rest of the message.
```php
Zend\Validator\AbstractValidator::setMessageLength(100);
```
> ### Where is this parameter used?
>
> The set message length is used for all validators, even for self defined ones,
> as long as they extend `Zend\Validator\AbstractValidator`.

View File

@@ -0,0 +1,45 @@
# Standard Validation Classes
The following validators come with the zend-validator distribution.
- [Barcode](validators/barcode.md)
- [Between](validators/between.md)
- [Callback](validators/callback.md)
- [CreditCard](validators/credit-card.md)
- [Date](validators/date.md)
- [RecordExists and NoRecordExists (database)](validators/db.md)
- [Digits](validators/digits.md)
- [EmailAddress](validators/email-address.md)
- [File Validation Classes](validators/file/intro.md)
- [GreaterThan](validators/greater-than.md)
- [Hex](validators/hex.md)
- [Hostname](validators/hostname.md)
- [Iban](validators/iban.md)
- [Identical](validators/identical.md)
- [InArray](validators/in-array.md)
- [Ip](validators/ip.md)
- [Isbn](validators/isbn.md)
- [IsInstanceOf](validators/isinstanceof.md)
- [LessThan](validators/less-than.md)
- [NotEmpty](validators/not-empty.md)
- [PostCode](validators/post-code.md)
- [Regex](validators/regex.md)
- [Sitemap](validators/sitemap.md)
- [Step](validators/step.md)
- [StringLength](validators/string-length.md)
- [Timezone](validators/timezone.md)
- [Uri](validators/uri.md)
- [Uuid](validators/uuid.md)
## Additional validators
Several other components offer validators as well:
- [zend-i18n](http://zendframework.github.io/zend-i18n/validators/)
## Deprecated Validators
### Ccnum
The `Ccnum` validator has been deprecated in favor of the `CreditCard`
validator. For security reasons you should use `CreditCard` instead of `Ccnum`.

View File

@@ -0,0 +1,96 @@
# Validator Chains
Often, multiple validations should be applied to some value in a particular
order. The following code demonstrates a way to solve the example from the
[introduction](intro.md), where a username must be between 6 and 12 alphanumeric
characters:
```php
use Zend\I18n\Validator\Alnum;
use Zend\Validator\StringLength;
use Zend\Validator\ValidatorChain;
// Create a validator chain and add validators to it
$chain = new ValidatorChain();
$chain->attach(new StringLength(['min' => 6, 'max' => 12]));
$chain->attach(new Alnum());
// Validate the username
if ($validatorChain->isValid($username)) {
// username passed validation
} else {
// username failed validation; print reasons
foreach ($validatorChain->getMessages() as $message) {
echo "$message\n";
}
}
```
Validators are run in the order they were added to the `ValidatorChain`. In the
above example, the username is first checked to ensure that its length is
between 6 and 12 characters, and then it is checked to ensure that it contains
only alphanumeric characters. The second validation, for alphanumeric
characters, is performed regardless of whether the first validation, for length
between 6 and 12 characters, succeeds. This means that if both validations fail,
`getMessages()` will return failure messages from both validators.
In some cases, it makes sense to have a validator *break the chain* if its
validation process fails. `ValidatorChain` supports such use cases with the
second parameter to the `attach()` method. By setting `$breakChainOnFailure` to
`true`, if the validator fails, it will short-circuit execution of the chain,
preventing subsequent validators from executing. If the above example were
written as follows, then the alphanumeric validation would not occur if the
string length validation fails:
```php
$chain->attach(new StringLength(['min' => 6, 'max' => 12], true));
$chain->attach(new Alnum());
```
Any object that implements `Zend\Validator\ValidatorInterface` may be used in a
validator chain.
## Setting Validator Chain Order
For each validator added to the `ValidatorChain`, you can set a *priority* to
define the chain order. The default value is `1`. Higher values indicate earlier
execution, while lower values execute later; use negative values to force late
execution.
In the following example, the username is first checked to ensure that its
length is between 7 and 9 characters, and then it is checked to ensure that its
length is between 3 and 5 characters.
```php
use Zend\I18n\Validator\Alnum;
use Zend\Validator\StringLength;
use Zend\Validator\ValidatorChain;
$username = 'ABCDFE';
// Create a validator chain and add validators to it
$chain = new ValidatorChain();
$chain->attach(
new StringLength(['min' => 3, 'max' => 5]),
true, // break chain on failure
1
);
$chain->attach(
new StringLength(['min' => 7, 'max' => 9]),
true, // break chain on failure
2 // higher priority!
);
// Validate the username
if ($validatorChain->isValid($username)) {
// username passed validation
echo "Success";
} else {
// username failed validation; print reasons
foreach ($validatorChain->getMessages() as $message) {
echo "$message\n";
}
}
// This first example will display: The input is less than 7 characters long
```

View File

@@ -0,0 +1,358 @@
# Barcode Validator
`Zend\Validator\Barcode` allows you to check if a given value can be represented
as a barcode.
## Supported barcodes
`Zend\Validator\Barcode` supports multiple barcode standards and can be extended
with proprietary barcode implementations. The following barcode standards are
supported:
### CODABAR
Also known as Code-a-bar.
This barcode has no length limitation. It supports only digits, and 6 special
chars. Codabar is a self-checking barcode. This standard is very old. Common use
cases are within airbills or photo labs where multi-part forms are used with
dot-matrix printers.
### CODE128
CODE128 is a high density barcode.
This barcode has no length limitation. It supports the first 128 ascii
characters. When used with printing characters it has an checksum which is
calculated modulo 103. This standard is used worldwide as it supports upper and
lowercase characters.
### CODE25
Often called "two of five" or "Code25 Industrial".
This barcode has no length limitation. It supports only digits, and the last
digit can be an optional checksum which is calculated with modulo 10. This
standard is very old and nowadays not often used. Common use cases are within
the industry.
### CODE25INTERLEAVED
Often called "Code 2 of 5 Interleaved".
This standard is a variant of CODE25. It has no length limitation, but it must
contain an even amount of characters. It supports only digits, and the last
digit can be an optional checksum which is calculated with modulo 10. It is used
worldwide and common on the market.
### CODE39
CODE39 is one of the oldest available codes.
This barcode has a variable length. It supports digits, upper cased alphabetical
characters and 7 special characters like whitespace, point and dollar sign. It
can have an optional checksum which is calculated with modulo 43. This standard
is used worldwide and common within the industry.
### CODE39EXT
CODE39EXT is an extension of CODE39.
This barcode has the same properties as CODE39. Additionally it allows the usage
of all 128 ASCII characters. This standard is used worldwide and common within
the industry.
### CODE93
CODE93 is the successor of CODE39.
This barcode has a variable length. It supports digits, alphabetical characters
and 7 special characters. It has an optional checksum which is calculated with
modulo 47 and contains 2 characters. This standard produces a denser code than
CODE39 and is more secure.
### CODE93EXT
CODE93EXT is an extension of CODE93.
This barcode has the same properties as CODE93. Additionally it allows the usage
of all 128 ASCII characters. This standard is used worldwide and common within
the industry.
### EAN2
EAN is the shortcut for "European Article Number".
These barcode must have 2 characters. It supports only digits and does not have
a checksum. This standard is mainly used as addition to EAN13 (ISBN) when
printed on books.
### EAN5
EAN is the shortcut for "European Article Number".
These barcode must have 5 characters. It supports only digits and does not have
a checksum. This standard is mainly used as addition to EAN13 (ISBN) when
printed on books.
### EAN8
EAN is the shortcut for "European Article Number".
These barcode can have 7 or 8 characters. It supports only digits. When it has a
length of 8 characters it includes a checksum. This standard is used worldwide
but has a very limited range. It can be found on small articles where a longer
barcode could not be printed.
### EAN12
EAN is the shortcut for "European Article Number".
This barcode must have a length of 12 characters. It supports only digits, and
the last digit is always a checksum which is calculated with modulo 10. This
standard is used within the USA and common on the market. It has been superseded
by EAN13.
### EAN13
EAN is the shortcut for "European Article Number".
This barcode must have a length of 13 characters. It supports only digits, and
the last digit is always a checksum which is calculated with modulo 10. This
standard is used worldwide and common on the market.
### EAN14
EAN is the shortcut for "European Article Number".
This barcode must have a length of 14 characters. It supports only digits, and
the last digit is always a checksum which is calculated with modulo 10. This
standard is used worldwide and common on the market. It is the successor for
EAN13.
### EAN18
EAN is the shortcut for "European Article Number".
This barcode must have a length of 18 characters. It support only digits. The
last digit is always a checksum digit which is calculated with modulo 10. This
code is often used for the identification of shipping containers.
### GTIN12
GTIN is the shortcut for "Global Trade Item Number".
This barcode uses the same standard as EAN12 and is its successor. It's commonly
used within the USA.
### GTIN13
GTIN is the shortcut for "Global Trade Item Number".
This barcode uses the same standard as EAN13 and is its successor. It is used
worldwide by industry.
### GTIN14
GTIN is the shortcut for "Global Trade Item Number".
This barcode uses the same standard as EAN14 and is its successor. It is used
worldwide and common on the market.
### IDENTCODE
Identcode is used by Deutsche Post and DHL. It's an specialized implementation of Code25.
This barcode must have a length of 12 characters. It supports only digits, and
the last digit is always a checksum which is calculated with modulo 10. This
standard is mainly used by the companies DP and DHL.
### INTELLIGENTMAIL
Intelligent Mail is a postal barcode.
This barcode can have a length of 20, 25, 29 or 31 characters. It supports only
digits, and contains no checksum. This standard is the successor of PLANET and
POSTNET. It is mainly used by the United States Postal Services.
### ISSN
ISSN is the abbreviation for International Standard Serial Number.
This barcode can have a length of 8 or 13 characters. It supports only digits,
and the last digit must be a checksum digit which is calculated with modulo 11.
It is used worldwide for printed publications.
### ITF14
ITF14 is the GS1 implementation of an Interleaved Two of Five bar code.
This barcode is a special variant of Interleaved 2 of 5. It must have a length
of 14 characters and is based on GTIN14. It supports only digits, and the last
digit must be a checksum digit which is calculated with modulo 10. It is used
worldwide and common within the market.
### LEITCODE
Leitcode is used by Deutsche Post and DHL. It's an specialized implementation of Code25.
This barcode must have a length of 14 characters. It supports only digits, and
the last digit is always a checksum which is calculated with modulo 10. This
standard is mainly used by the companies DP and DHL.
### PLANET
Planet is the abbreviation for Postal Alpha Numeric Encoding Technique.
This barcode can have a length of 12 or 14 characters. It supports only digits,
and the last digit is always a checksum. This standard is mainly used by the
United States Postal Services.
### POSTNET
Postnet is used by the US Postal Service.
This barcode can have a length of 6, 7, 10 or 12 characters. It supports only
digits, and the last digit is always a checksum. This standard is mainly used by
the United States Postal Services.
### ROYALMAIL
Royalmail is used by Royal Mail.
This barcode has no defined length. It supports digits, uppercase letters, and
the last digit is always a checksum. This standard is mainly used by Royal Mail
for their Cleanmail Service. It is also called RM4SCC.
### SSCC
SSCC is the shortcut for "Serial Shipping Container Code".
This barcode is a variant of EAN barcode. It must have a length of 18 characters
and supports only digits. The last digit must be a checksum digit which is
calculated with modulo 10. It is commonly used by the transport industry.
### UPCA
UPC is the shortcut for "Universal Product Code".
This barcode preceded EAN13. It must have a length of 12 characters and supports
only digits. The last digit must be a checksum digit which is calculated with
modulo 10. It is commonly used within the USA.
### UPCE
UPCE is the short variant from UPCA.
This barcode is a smaller variant of UPCA. It can have a length of 6, 7 or 8
characters and supports only digits. When the barcode is 8 chars long it
includes a checksum which is calculated with modulo 10. It is commonly used with
small products where a UPCA barcode would not fit.
## Supported options
The following options are supported for `Zend\Validator\Barcode`:
- `adapter`: Sets the barcode adapter which will be used. Supported are all
above noted adapters. When using a self defined adapter, then you have to set
the complete class name.
- `checksum`: `TRUE` when the barcode should contain a checksum. The default
value depends on the used adapter. Note that some adapters don't allow to set
this option.
- `options`: Defines optional options for a self written adapters.
## Basic usage
To validate if a given string is a barcode you must know its type. See the
following example for an EAN13 barcode:
```php
$valid = new Zend\Validator\Barcode('EAN13');
if ($valid->isValid($input)) {
// input appears to be valid
} else {
// input is invalid
}
```
## Optional checksum
Some barcodes can be provided with an optional checksum. These barcodes would be
valid even without checksum. Still, when you provide a checksum, then you should
also validate it. By default, these barcode types perform no checksum
validation. By using the `checksum` option you can define if the checksum will
be validated or ignored.
```php
$valid = new Zend\Validator\Barcode([
'adapter' => 'EAN13',
'checksum' => false,
]);
if ($valid->isValid($input)) {
// input appears to be valid
} else {
// input is invalid
}
```
> ### Reduced security by disabling checksum validation
>
> By switching off checksum validation you will also reduce the security of the
> used barcodes. Additionally you should note that you can also turn off the
> checksum validation for those barcode types which must contain a checksum
> value. Barcodes which would not be valid could then be returned as valid even
> if they are not.
## Writing custom adapters
You may write custom barcode validators for usage with `Zend\Validator\Barcode`;
this is often necessary when dealing with proprietary barcode types. To write
your own barcode validator, you need the following information.
- `Length`: The length your barcode must have. It can have one of the following
values:
- `Integer`: A value greater 0, which means that the barcode must have this
length.
- `-1`: There is no limitation for the length of this barcode.
- `"even"`: The length of this barcode must have a even amount of digits.
- `"odd"`: The length of this barcode must have a odd amount of digits.
- `array`: An array of integer values. The length of this barcode must have
one of the set array values.
- `Characters`: A string which contains all allowed characters for this barcode.
Also the integer value 128 is allowed, which means the first 128 characters of
the ASCII table.
- `Checksum`: A string which will be used as callback for a method which does
the checksum validation.
Your custom barcode validator must extend `Zend\Validator\Barcode\AbstractAdapter`
or implement `Zend\Validator\Barcode\AdapterInterface`.
As an example, let's create a validator that expects an even number of
characters that include all digits and the letters 'ABCDE', and which requires a
checksum.
```php
namespace My\Barcode;
use Zend\Validator\Barcode;
use Zend\Validator\Barcode\AbstractAdapter;
class MyBar extends AbstractAdapter
{
protected $length = 'even';
protected $characters = '0123456789ABCDE';
protected $checksum = 'mod66';
protected function mod66($barcode)
{
// do some validations and return a boolean
}
}
$valid = Barcode(MyBar::class);
if ($valid->isValid($input)) {
// input appears to be valid
} else {
// input is invalid
}
```

View File

@@ -0,0 +1,54 @@
# Between Validator
`Zend\Validator\Between` allows you to validate if a given value is between two
other values.
> ### Only supports number validation
>
> `Zend\Validator\Between` supports only the validation of numbers. Strings or
> dates can not be validated with this validator.
## Supported options
The following options are supported for `Zend\Validator\Between`:
- `inclusive`: Defines if the validation is inclusive of the minimum and maximum
border values, or exclusive. It defaults to `true`.
- `max`: Sets the maximum border for the validation.
- `min`: Sets the minimum border for the validation.
## Default behaviour
Per default, this validator checks if a value is between `min` and `max` where
both border values are allowed as value.
```php
$valid = new Zend\Validator\Between(['min' => 0, 'max' => 10]);
$value = 10;
$result = $valid->isValid($value);
// returns true
```
In the above example, the result is `true` due to the reason that the default
search is inclusive of the border values. This means in our case that any value
from '0' to '10' is allowed; values like '-1' and '11' will return `false`.
## Excluding border values
Sometimes it is useful to validate a value by excluding the border values. See
the following example:
```php
$valid = new Zend\Validator\Between([
'min' => 0,
'max' => 10,
'inclusive' => false,
]);
$value = 10;
$result = $valid->isValid($value);
// returns false
```
The example above is almost identical to our first example, but we now exclue
the border values; as such, the values '0' and '10' are no longer allowed and
will return `false`.

View File

@@ -0,0 +1,203 @@
# Callback Validator
`Zend\Validator\Callback` allows you to provide a callback with which to
validate a given value.
## Supported options
The following options are supported for `Zend\Validator\Callback`:
- `callback`: Sets the callback which will be called for the validation.
- `options`: Sets the additional options which will be given to the validator
and/or callback.
## Basic usage
The simplest use case is to pass a function as a callback. Consider the
following function:
```php
function myMethod($value)
{
// some validation
return true;
}
```
To use it within `Zend\Validator\Callback`, pass it to the constructor
```php
$valid = new Zend\Validator\Callback('myMethod');
if ($valid->isValid($input)) {
// input appears to be valid
} else {
// input is invalid
}
```
## Usage with closures
The `Callback` validator supports any PHP callable, including PHP
[closures](http://php.net/functions.anonymous).
```php
$valid = new Zend\Validator\Callback(function($value) {
// some validation
return true;
});
if ($valid->isValid($input)) {
// input appears to be valid
} else {
// input is invalid
}
```
## Usage with class-based callbacks
Of course it's also possible to use a class method as callback. Consider the
following class definition:
```php
class MyClass
{
public function myMethod($value)
{
// some validation
return true;
}
}
```
To use it with the `Callback` validator, pass a callable using an instance of
the class:
```php
$valid = new Zend\Validator\Callback([new MyClass, 'myMethod']);
if ($valid->isValid($input)) {
// input appears to be valid
} else {
// input is invalid
}
```
You may also define a static method as a callback. Consider the following class
definition and validator usage:
```php
class MyClass
{
public static function test($value)
{
// some validation
return true;
}
}
$valid = new Zend\Validator\Callback(MyClass::class, 'test']);
if ($valid->isValid($input)) {
// input appears to be valid
} else {
// input is invalid
}
```
Finally, you may define the magic method `__invoke()` in your class. If you do
so, you can provide a class instance itself as the callback:
```php
class MyClass
{
public function __invoke($value)
{
// some validation
return true;
}
}
$valid = new Zend\Validator\Callback(new MyClass());
if ($valid->isValid($input)) {
// input appears to be valid
} else {
// input is invalid
}
```
## Adding options
`Zend\Validator\Callback` also allows the usage of options which are provided as
additional arguments to the callback.
Consider the following class and method definition:
```php
class MyClass
{
public static function myMethod($value, $option)
{
// some validation
return true;
}
/**
* Or, to use with contextual validation
*/
public static function myMethod($value, $context, $option)
{
// some validation
return true;
}
}
```
There are two ways to inform the validator of additional options: pass them in
the constructor, or pass them to the `setOptions()` method.
To pass them to the constructor, you would need to pass an array containing two
keys, `callback` and `callbackOptions`:
```php
$valid = new Zend\Validator\Callback([
'callback' => [MyClass::class, 'myMethod'],
'callbackOptions' => $options,
]);
if ($valid->isValid($input)) {
// input appears to be valid
} else {
// input is invalid
}
```
Otherwise, you may pass them to the validator after instantiation:
```php
$valid = new Zend\Validator\Callback([MyClass::class, 'myMethod']);
$valid->setOptions($options);
if ($valid->isValid($input)) {
// input appears to be valid
} else {
// input is invalid
}
```
When there are additional values given to `isValid()`, then these values will be
passed as an additional argument:
```php
$valid = new Zend\Validator\Callback([MyClass::class, 'myMethod']);
$valid->setOptions($options);
if ($valid->isValid($input, $context)) {
// input appears to be valid
} else {
// input is invalid
}
```
When making the call to the callback, the value to be validated will always be
passed as the first argument to the callback followed by all other values given
to `isValid()`; all other options will follow it. The amount and type of options
which can be used is not limited.

View File

@@ -0,0 +1,172 @@
# CreditCard Validator
`Zend\Validator\CreditCard` allows you to validate if a given value could be a
credit card number.
A credit card contains several items of metadata, including a hologram, account
number, logo, expiration date, security code, and the card holder name. The
algorithms for verifying the combination of metadata are only known to the
issuing company, and should be verified with them for purposes of payment.
However, it's often useful to know whether or not a given number actually falls
within the ranges of possible numbers **prior** to performing such verification,
and, as such, `Zend\Validator\CreditCard` verifies that the credit card number
provided is well-formed.
For those cases where you have a service that can perform comprehensive
verification, `Zend\Validator\CreditCard` also provides the ability to attach a
service callback to trigger once the credit card number has been deemed valid;
this callback will then be triggered, and its return value will determine
overall validity.
The following issuing institutes are accepted:
- American Express
- China UnionPay
- Diners Club Card Blanche
- Diners Club International
- Diners Club US and Canada
- Discover Card
- JCB
- Laser
- Maestro
- MasterCard
- Solo
- Visa
- Visa Electron
> ### Invalid institutes
>
> The institutes **Bankcard** and **Diners Club enRoute** no longer exist, and
> are treated as invalid.
>
> **Switch** has been rebranded to **Visa** and is therefore also treated as
> invalid.
## Supported options
The following options are supported for `Zend\Validator\CreditCard`:
- `service`: A callback to an online service which will additionally be used for
the validation.
- `type`: The type of credit card which will be validated. See the below list of
institutes for details.
## Basic usage
There are several credit card institutes which can be validated by
`Zend\Validator\CreditCard`. Per default, all known institutes will be accepted.
See the following example:
```php
$valid = new Zend\Validator\CreditCard();
if ($valid->isValid($input)) {
// input appears to be valid
} else {
// input is invalid
}
```
The above example would validate against all known credit card institutes.
## Accepting only specific credit cards
Sometimes it is necessary to accept only specific credit card institutes instead
of all; e.g., when you have a webshop which accepts only Visa and American
Express cards. `Zend\Validator\CreditCard` allows you to do exactly this by
limiting it to exactly these institutes.
To use a limitation you can either provide specific institutes at initiation, or
afterwards by using `setType()`. Each can take several arguments.
You can provide a single institute:
```php
use Zend\Validator\CreditCard;
$valid = new CreditCard(CreditCard::AMERICAN_EXPRESS);
```
When you want to allow multiple institutes, then you can provide them as array:
```php
use Zend\Validator\CreditCard;
$valid = new CreditCard([
CreditCard::AMERICAN_EXPRESS,
CreditCard::VISA
]);
```
And, as with all validators, you can also pass an associative array of options
or an instance of `Traversable`. In this case you have to provide the institutes
with the `type` array key as demostrated here:
```php
use Zend\Validator\CreditCard;
$valid = new CreditCard([
'type' => [CreditCard::AMERICAN_EXPRESS]
]);
```
You can also manipulate institutes after instantiation by using the methods
`setType()`, `addType()`, and `getType()`.
```php
use Zend\Validator\CreditCard;
$valid = new CreditCard();
$valid->setType([
CreditCard::AMERICAN_EXPRESS,
CreditCard::VISA
]);
```
> ### Default institute
>
> When no institute is given at initiation then `ALL` will be used, which sets
> all institutes at once.
>
> In this case the usage of `addType()` is useless because all institutes are
> already added.
## Validation using APIs
As said before `Zend\Validator\CreditCard` will only validate the credit card
number. Fortunately, some institutes provide online APIs which can validate a
credit card number by using algorithms which are not available to the public.
Most of these services are paid services. Therefore, this check is deactivated
per default.
When you have access to such an API, then you can use it as an add on for
`Zend\Validator\CreditCard` and increase the security of the validation.
To do so, provide a callback to invoke when generic validation has passed. This
prevents the API from being called for invalid numbers, which increases the
performance of the application.
`setService()` sets a new service, and `getService()` returns the set service.
As a configuration option, you can give the array key `service` at instantiatio.
For details about possible options, read the
[Callback validator documentation](callback.md).
```php
use Zend\Validator\CreditCard;
// Your service class
class CcService
{
public function checkOnline($cardnumber, $types)
{
// some online validation
}
}
// The validation
$service = new CcService();
$valid = new CreditCard(CreditCard::VISA);
$valid->setService([$service, 'checkOnline']);
```
The callback method will be called with the credit card number as the first
parameter, and the accepted types as the second parameter.

View File

@@ -0,0 +1,35 @@
# Date Validator
`Zend\Validator\Date` allows you to validate if a given value contains a date.
## Supported options
The following options are supported for `Zend\Validator\Date`:
- `format`: Sets the format which is used to write the date.
- `locale`: Sets the locale which will be used to validate date values.
## Default date validation
The easiest way to validate a date is by using the default date format,
`Y-m-d`.
```php
$validator = new Zend\Validator\Date();
$validator->isValid('2000-10-10'); // returns true
$validator->isValid('10.10.2000'); // returns false
```
## Specifying a date format
`Zend\Validator\Date` also supports custom date formats. When you want to
validate such a date, use the `format` option. This option accepts any format
allowed by the PHP [date()](http://php.net/date) function.
```php
$validator = new Zend\Validator\Date(['format' => 'Y']);
$validator->isValid('2010'); // returns true
$validator->isValid('May'); // returns false
```

View File

@@ -0,0 +1,180 @@
# Db\\RecordExists and Db\\NoRecordExists Validators
`Zend\Validator\Db\RecordExists` and `Zend\Validator\Db\NoRecordExists` provide
a means to test whether a record exists in a given table of a database, with a
given value.
## Supported options
The following options are supported for `Zend\Validator\Db\NoRecordExists` and
`Zend\Validator\Db\RecordExists`:
- `adapter`: The database adapter that will be used for the search.
- `exclude`: Sets records that will be excluded from the search.
- `field`: The database field within this table that will be searched for the record.
- `schema`: Sets the schema that will be used for the search.
- `table`: The table that will be searched for the record.
## Basic usage
An example of basic usage of the validators:
```php
// Check that the email address exists in the database
$validator = new Zend\Validator\Db\RecordExists([
'table' => 'users',
'field' => 'emailaddress',
'adapter' => $dbAdapter,
]);
if ($validator->isValid($emailaddress)) {
// email address appears to be valid
} else {
// email address is invalid; print the reasons
foreach ($validator->getMessages() as $message) {
echo "$message\n";
}
}
```
The above will test that a given email address is in the database table. If no
record is found containing the value of `$emailaddress` in the specified column,
then an error message is displayed.
```php
// Check that the username is not present in the database
$validator = new Zend\Validator\Db\NoRecordExists([
'table' => 'users',
'field' => 'username',
'adapter' => $dbAdapter,
]);
if ($validator->isValid($username)) {
// username appears to be valid
} else {
// username is invalid; print the reason
$messages = $validator->getMessages();
foreach ($messages as $message) {
echo "$message\n";
}
}
```
The above will test that a given username is *not* in the database table. If a
record is found containing the value of `$username` in the specified column,
then an error message is displayed.
## Excluding records
`Zend\Validator\Db\RecordExists` and `Zend\Validator\Db\NoRecordExists` also
provide a means to test the database, excluding a part of the table, either by
providing a `WHERE` clause as a string, or an array with the keys `field` and
`value`.
When providing an array for the exclude clause, the `!=` operator is used, so
you can check the rest of a table for a value before altering a record (for
example on a user profile form)
```php
// Check no other users have the username
$user_id = $user->getId();
$validator = new Zend\Validator\Db\NoRecordExists([
'table' => 'users',
'field' => 'username',
'exclude' => [
'field' => 'id',
'value' => $user_id,
],
]);
if ($validator->isValid($username)) {
// username appears to be valid
} else {
// username is invalid; print the reason
$messages = $validator->getMessages();
foreach ($messages as $message) {
echo "$message\n";
}
}
```
The above example will check the table to ensure no records other than the one
where `id = $user_id` contains the value `$username`.
You can also provide a string to the exclude clause so you can use an operator
other than `!=`. This can be useful for testing against composite keys.
```php
$email = 'user@example.com';
$clause = $dbAdapter->quoteIdentifier('email') . ' = ' . $dbAdapter->quoteValue($email);
$validator = new Zend\Validator\Db\RecordExists([
'table' => 'users',
'field' => 'username',
'adapter' => $dbAdapter,
'exclude' => $clause,
]);
if ($validator->isValid($username)) {
// username appears to be valid
} else {
// username is invalid; print the reason
$messages = $validator->getMessages();
foreach ($messages as $message) {
echo "$message\n";
}
}
```
The above example will check the `users` table to ensure that only a record with
both the username `$username` and with the email `$email` is valid.
## Database Schemas
You can specify a schema within your database for adapters such as PostgreSQL
and DB/2 by supplying an array with `table` and `schema` keys, as demonstrated
below:
```php
$validator = new Zend\Validator\Db\RecordExists([
'table' => 'users',
'schema' => 'my',
'field' => 'id',
]);
```
## Using a Select object
It is also possible to supply the validators with a `Zend\Db\Sql\Select` object
in place of options. The validator then uses this object instead of building its
own. This allows for greater flexibility with selection of records used for
validation.
```php
use Zend\Db\Sql\Select;
use Zend\Validator\Db\RecordExists;
$select = new Select();
$select
->from('users')
->where->equalTo('id', $user_id)
->where->equalTo('email', $email);
$validator = new RecordExists($select);
// We still need to set our database adapter
$validator->setAdapter($dbAdapter);
// Validation is then performed as usual
if ($validator->isValid($username)) {
// username appears to be valid
} else {
// username is invalid; print the reason
$messages = $validator->getMessages();
foreach ($messages as $message) {
echo "$message\n";
}
}
```
The above example will check the `users` table to ensure that only a record with
both the username `$username` and with the email `$email` is valid.

View File

@@ -0,0 +1,27 @@
# Digits Validator
`Zend\Validator\Digits` validates if a given value contains only digits.
## Supported options
There are no additional options for `Zend\Validator\Digits`:
## Validating digits
To validate if a given value contains only digits and no other characters,
call the validator as shown below:
```php
$validator = new Zend\Validator\Digits();
$validator->isValid("1234567890"); // returns true
$validator->isValid(1234); // returns true
$validator->isValid('1a234'); // returns false
```
> ### Validating numbers
>
> When you want to validate numbers or numeric values, be aware that this
> validator only validates *digits*. This means that any other sign like a
> thousand separator or a comma will not pass this validator. In this case you
> should use `Zend\I18n\Validator\IsInt` or `Zend\I18n\Validator\IsFloat`.

View File

@@ -0,0 +1,201 @@
# EmailAddress Validator
`Zend\Validator\EmailAddress` allows you to validate an email address. The
validator first splits the email address on `local-part @ hostname` and attempts
to match these against known specifications for email addresses and hostnames.
## Basic usage
A basic example of usage is below:
```php
$validator = new Zend\Validator\EmailAddress();
if ($validator->isValid($email)) {
// email appears to be valid
} else {
// email is invalid; print the reasons
foreach ($validator->getMessages() as $message) {
echo "$message\n";
}
}
```
This will match the email address `$email` and on failure populate
`getMessages()` with useful error messages.
## Supported Options
`Zend\Validator\EmailAddress` supports several options which can either be set
at instantiation, by giving an array with the related options, or afterwards, by
using `setOptions()`. The following options are supported:
- `allow`: Defines which type of domain names are accepted. This option is used
in conjunction with the hostname option to set the hostname validator. For
more information about possible values of this option, look at
[Hostname](hostname.md) and possible `ALLOW_*` constants. This option
defaults to `ALLOW_DNS`.
- `deep`: Defines if the servers MX records should be verified by a deep check.
When this option is set to `true` then additionally to MX records also the `A`,
`A6` and `AAAA` records are used to verify if the server accepts emails. This
option defaults to `false`.
- `domain`: Defines if the domain part should be checked. When this option is
set to `false`, then only the local part of the email address will be checked.
In this case the hostname validator will not be called. This option defaults
to `true`.
- `hostname`: Sets the hostname validator with which the domain part of the
email address will be validated.
- `mx`: Defines if the MX records from the server should be detected. If this
option is defined to `true` then the MX records are used to verify if the
server accepts emails. This option defaults to `false`.
## Complex local parts
`Zend\Validator\EmailAddress` will match any valid email address according to
RFC2822. For example, valid emails include `bob@domain.com`,
`bob+jones@domain.us`, `"bob@jones"@domain.com*` and `"bob jones"@domain.com`
Some obsolete email formats will not currently validate (e.g. carriage returns
or a `\\` character in an email address).
## Validating only the local part
If you need `Zend\Validator\EmailAddress` to check only the local part of an
email address, and want to disable validation of the hostname, you can set the
`domain` option to `false`. This forces `Zend\Validator\EmailAddress` not to
validate the hostname part of the email address.
```php
$validator = new Zend\Validator\EmailAddress();
$validator->setOptions(['domain' => FALSE]);
```
## Validating different types of hostnames
The hostname part of an email address is validated against the [Hostname validator](hostname.md).
By default only DNS hostnames of the form `domain.com` are accepted, though if
you wish you can accept IP addresses and Local hostnames too.
To do this you need to instantiate `Zend\Validator\EmailAddress` passing a
parameter to indicate the type of hostnames you want to accept. More details are
included in `Zend\Validator\Hostname`, though an example of how to accept both
DNS and Local hostnames appears below:
```php
use Zend\Validator\EmailAddress;
use Zend\Validator\Hostname;
$validator = new EmailAddress( Hostname::ALLOW_DNS | Hostname::ALLOW_LOCAL);
if ($validator->isValid($email)) {
// email appears to be valid
} else {
// email is invalid; print the reasons
foreach ($validator->getMessages() as $message) {
echo "$message\n";
}
}
```
## Checking if the hostname actually accepts email
Just because an email address is in the correct format, it doesn't necessarily
mean that email address actually exists. To help solve this problem, you can use
MX validation to check whether an MX (email) entry exists in the DNS record for
the email's hostname. This tells you that the hostname accepts email, but
doesn't tell you the exact email address itself is valid.
MX checking is not enabled by default. To enable MX checking you can pass a
second parameter to the `Zend\Validator\EmailAddress` constructor.
```php
$validator = new Zend\Validator\EmailAddress([
'allow' => Zend\Validator\Hostname::ALLOW_DNS,
'useMxCheck' => true,
]);
```
Alternatively you can either pass `true` or `false` to `setValidateMx()` to
enable or disable MX validation.
By enabling this setting, network functions will be used to check for the
presence of an MX record on the hostname of the email address you wish to
validate. Please be aware this will likely slow your script down.
Sometimes validation for MX records returns `false`, even if emails are
accepted. The reason behind this behaviour is, that servers can accept emails
even if they do not provide a MX record. In this case they can provide `A`,
`A6`, or `AAAA` records. To allow `Zend\Validator\EmailAddress` to check also
for these other records, you need to set deep MX validation. This can be done at
initiation by setting the `deep` option or by using `setOptions()`.
```php
$validator = new Zend\Validator\EmailAddress([
'allow' => Zend\Validator\Hostname::ALLOW_DNS,
'useMxCheck' => true,
'useDeepMxCheck' => true,
]);
```
Sometimes it can be useful to get the server's MX information which have been
used to do further processing. Simply use `getMXRecord()` after validation. This
method returns the received MX record including weight and sorted by it.
> ### Performance warning**
>
> You should be aware that enabling MX check will slow down you script because
> of the used network functions. Enabling deep check will slow down your script
> even more as it searches the given server for 3 additional types.
> ### Disallowed IP addresses
>
> You should note that MX validation is only accepted for external servers. When
> deep MX validation is enabled, then local IP addresses like `192.168.*` or
> `169.254.*` are not accepted.
## Validating International Domains Names
`Zend\Validator\EmailAddress` will also match international characters that
exist in some domains. This is known as International Domain Name (IDN) support.
This is enabled by default, though you can disable this by changing the setting
via the internal `Zend\Validator\Hostname` object that exists within
`Zend\Validator\EmailAddress`.
```php
$validator->getHostnameValidator()->setValidateIdn(false);
```
More information on the usage of `setValidateIdn()` appears in the
[Hostname documentation](hostname.md).
Please note IDNs are only validated if you allow DNS hostnames to be validated.
## Validating Top Level Domains
By default a hostname will be checked against a list of known TLDs. This is
enabled by default, though you can disable this by changing the setting via the
internal `Zend\Validator\Hostname` object that exists within
`Zend\Validator\EmailAddress`.
```php
$validator->getHostnameValidator()->setValidateTld(false);
```
More information on the usage of `setValidateTld()` appears in the
[Hostname documentation](hostname.md).
Please note TLDs are only validated if you allow DNS hostnames to be validated.
## Setting messages
`Zend\Validator\EmailAddress` makes also use of `Zend\Validator\Hostname` to
check the hostname part of a given email address. You can specify messages for
`Zend\Validator\Hostname` from within `Zend\Validator\EmailAddress`.
```php
$validator = new Zend\Validator\EmailAddress();
$validator->setMessages([
Zend\Validator\Hostname::UNKNOWN_TLD => 'I don\'t know the TLD you gave'
]);
```

View File

@@ -0,0 +1,31 @@
# Count
`Zend\Validator\File\Count` allows you to validate that the number of files
uploaded matches criteria, including a minimum number of files and/or a maximum
number of files.
## Supported Options
The following options are supported:
- `min`: The minimum number of uploaded files acceptable; `null` is equivalent
to `0`, indicating no minimum.
- `max`: The maximum number of uploaded files acceptable; `null` is equivalent
to no maximum.
## Basic Usage
```php
$validator = new Zend\Validator\File\Count([
'min' => 1,
'max' => 5,
]);
// Setting to the $_FILES superglobal; could also use the zend-http
// request's `getFiles()` or PSR-7 ServerRequest's `getUploadedFiles()`.
$files = $_FILES;
if ($validator->isValid($files)) {
// Received between 1 and 5 files!
}
```

View File

@@ -0,0 +1,60 @@
# Crc32
`Zend\Validator\File\Crc32` allows you to validate if a given file's hashed
contents matches the supplied crc32 hash(es). It is subclassed from the [Hash
validator](hash.md) to provide a validator that only supports the `crc32`
algorithm.
> ### Requires the hash extension
>
> This validator requires the PHP [Hash extension](http://php.net/hash) with the
> `crc32` algorithm.
## Supported Options
The following options are supported:
- `hash`: Single string hash to test the file against, or array of filename/hash
pairs.
## Usage Examples
```php
// Does file have the given hash?
$validator = new \Zend\Validator\File\Crc32('3b3652f');
// Or, check file against multiple hashes
$validator = new \Zend\Validator\File\Crc32(array('3b3652f', 'e612b69'));
// Perform validation with file path
if ($validator->isValid('./myfile.txt')) {
// file is valid
}
```
## Public Methods
### getCrc32
```php
getCrc32() : array
```
Returns an array of all currently registered hashes to test against.
### addCrc32
```php
addCrc32(string|array $options) : void
```
Add a single hash to test against, or a set of filename/hash pairs to test
against.
### setCrc32
```php
setCrc32(string|array $options): void
```
Overwrite the current list of registered hashes with the one(s) provided.

View File

@@ -0,0 +1,7 @@
# ExcludeExtension
`Zend\Validator\File\ExcludeExtension` checks the extension of files. It will
assert `false` when a given file matches any of the defined extensions.
This validator is inversely related to the [Extension validator](extension.md);
please refer to that validator for full options and usage examples.

View File

@@ -0,0 +1,9 @@
ExcludeMimeType
===============
`Zend\Validator\File\ExcludeMimeType` checks the MIME type of files. It will
assert `false` when a given file matches any of the defined MIME types.
This validator is inversely related to the [MimeType validator](mime-type.md);
please refer to that validator's documentation for full options and usage
examples.

View File

@@ -0,0 +1,35 @@
# Exists
`Zend\Validator\File\Exists` checks for the existence of files in specified
directories.
This validator is inversely related to the [NotExists validator](not-exists.md).
## Supported Options
The following set of options are supported:
- `directory`: Array of directories, or comma-delimited string of directories.
## Usage Examples
```php
use Zend\Validator\File\Exists;
// Only allow files that exist in ~both~ directories
$validator = new Exists('/tmp,/var/tmp');
// ...or with array notation
$validator = new Exists(['/tmp', '/var/tmp']);
// Perform validation
if ($validator->isValid('/tmp/myfile.txt')) {
// file is valid
}
```
> ### Checks against all directories
>
> This validator checks whether the specified file exists in **all** of the
> given directories; validation will fail if the file does not exist in one
> or more of them.

View File

@@ -0,0 +1,52 @@
# Extension
`Zend\Validator\File\Extension` checks the extension of files. It will assert
`true` when a given file matches any of the defined extensions.
This validator is inversely related to the
[ExcludeExtension validator](exclude-extension.md).
## Supported Options
The following set of options are supported:
- `extension`: Array of extensions, or comma-delimited string of extensions,
against which to test.
- `case`: Boolean indicating whether or not extensions should match case
sensitively; defaults to `false` (case-insensitive).
## Usage Examples
```php
use Zend\Validator\File\Extension;
// Allow files with 'php' or 'exe' extensions
$validator = new Extension('php,exe');
// ...or with array notation
$validator = new Extension(['php', 'exe']);
// Test with case-sensitivity on
$validator = new Extension(['php', 'exe'], true);
// Using an options array:
$validator = new Extension([
'extension' => ['php', 'exe'],
'case' => true,
]);
// Perform validation
if ($validator->isValid('./myfile.php')) {
// file is valid
}
```
## Public Methods
### addExtension
```php
addExtension(string|array $options) : void
```
Add one or more extensions as a comma-separated list, or as an array.

View File

@@ -0,0 +1,38 @@
# FilesSize
`Zend\Validator\File\FilesSize` allows validating the total size of all file
uploads in aggregate, allowing specifying a minimum upload size and/or a maximum
upload size.
Only use this validator if you will be expecting multiple file uploads in a
single payload, and want to ensure the aggregate size falls within a specific
range.
## Supported Options
`Zend\Validator\File\FilesSize` supports the following options:
- `min`: The minimum aggregate size of all file uploads. May be specified as an
integer or using SI units. `null` indicates no minimum size is required.
- `max`: The maximum aggregate size of all file uploads. May be specified as an
integer or using SI units. `null` indicates no maximum size is required.
- `useByteString`: A flag indicating whether sizes should be reported as
integers or using SI units when reporting validation errors.
See the [Size validator](size.md#supported-options) for details on supported SI
units.
## Basic Usage
```php
use Zend\Validator\File\FilesSize;
$validator = new FilesSize([
'min' => '1kB`, // minimum of 1kB
'max' => `10MB', // maximum of 10MB
]);
if ($validator->isValid($_FILES)) {
// > 1kB, < 10MB in aggregate
}
```

View File

@@ -0,0 +1,66 @@
# Hash
`Zend\Validator\File\Hash` allows you to validate if a given file's hashed
contents matches the supplied hash(es) and algorithm(s).
> ### Requires the hash extension
>
> This validator requires the PHP [Hash extension](http://php.net/hash). A list
> of supported hash algorithms can be found with the
> [hash\_algos() function](http://php.net/hash_algos).
## Supported Options
The following set of options are supported:
- `hash`: String hash or array of hashes against which to test.
- `algorithm`: String hashing algorithm to use; defaults to `crc32`
## Basic Usage
```php
use Zend\Validator\File\Hash;
// Does file have the given hash?
$validator = new Hash('3b3652f', 'crc32');
// Or, check file against multiple hashes
$validator = new Hash(['3b3652f', 'e612b69'], 'crc32');
// Or use options notation:
$validator = new Hash([
'hash' => ['3b3652f', 'e612b69'],
'algorithm' => 'crc32',
]);
// Perform validation with file path
if ($validator->isValid('./myfile.txt')) {
// file is valid
}
```
## Public Methods
### getHash
```php
getHash() : array
```
Returns an array containing the set of hashes against which to validate.
### addHash
```php
addHash(string|array $options) : void
```
Add one or more hashes against which to validate.
### setHash
```php
setHash(string|array $options) : void
```
Overwrite the current set of hashes with those provided to the method.

View File

@@ -0,0 +1,71 @@
# ImageSize
`Zend\Validator\File\ImageSize` checks the size of image files. Minimum and/or
maximum dimensions can be set to validate against.
## Supported Options
The following set of options are supported:
- `minWidth`: Set the minimum image width as an integer; `null` (the default)
indicates no minimum.
- `minHeight`: Set the minimum image height as an integer; `null` (the default)
indicates no minimum.
- `maxWidth`: Set the maximum image width as an integer; `null` (the default)
indicates no maximum.
- `maxHeight`: Set the maximum image height as an integer; `null` (the default)
indicates no maximum.
## Basic Usage
```php
use Zend\Validator\File\ImageSize;
// Is image size between 320x200 (min) and 640x480 (max)?
$validator = new ImageSize(320, 200, 640, 480);
// ...or with array notation
$validator = new ImageSize([
'minWidth' => 320,
'minHeight' => 200,
'maxWidth' => 640,
'maxHeight' => 480,
]);
// Is image size equal to or larger than 320x200?
$validator = new ImageSize([
'minWidth' => 320,
'minHeight' => 200,
]);
// Is image size equal to or smaller than 640x480?
$validator = new ImageSize([
'maxWidth' => 640,
'maxHeight' => 480,
]);
// Perform validation with file path
if ($validator->isValid('./myfile.jpg')) {
// file is valid
}
```
## Public Methods
### getImageMin
```php
getImageMin() : array
```
Returns the minimum valid dimensions as an array with the keys `width` and
`height`.
### getImageMax
```php
getImageMax() : array
```
Returns the maximum valid dimensions as an array with the keys `width` and
`height`.

View File

@@ -0,0 +1,30 @@
# File Validation Classes
Zend Framework comes with a set of classes for validating both files and
uploaded files, such as file size validation and CRC checking.
- [Count](count.md)
- [crc32](crc32.md)
- [ExcludeExtension](exclude-extension.md)
- [ExcludeMimeType](exclude-mime-type.md)
- [Exists](exists.md)
- [Extension](extension.md)
- [FilesSize](files-size.md)
- [Hash](hash.md)
- [ImageSize](image-size.md)
- [IsCompressed](is-compressed.md)
- [IsImage](is-image.md)
- [Md5](md5.md)
- [MimeType](mime-type.md)
- [NotExists](not-exists.md)
- [Sha1](sha1.md)
- [Size](size.md)
- [Upload](upload.md)
- [UploadFile](upload-file.md)
- [WordCount](word-count.md)
> ### Validation argument
>
> All of the File validators' `isValid()` methods support both a file path
> `string` *or* a `$_FILES` array as the supplied argument. When a `$_FILES`
> array is passed in, the `tmp_name` is used for the file path.

View File

@@ -0,0 +1,21 @@
# IsCompressed
`Zend\Validator\File\IsCompressed` checks if a file is a compressed archive,
such as zip or gzip. This validator is based on the
[MimeType validator](mime-type.md), and supports the same methods and options.
The default list of [compressed file MIME types](https://github.com/zendframework/zend-validator/blob/master/src/File/IsCompressed.php#L45)
can be found in the source code.
Please refer to the [MimeType validator](mime-type.md) for options and public
methods.
## Basic Usage
```php
$validator = new \Zend\Validator\File\IsCompressed();
if ($validator->isValid('./myfile.zip')) {
// file is valid
}
```

View File

@@ -0,0 +1,21 @@
# IsImage
`Zend\Validator\File\IsImage` checks if a file is an image, such as jpg or png.
This validator is based on the [MimeType validator](mime-type.md) and supports
the same methods and options.
The default list of [image file MIME types](https://github.com/zendframework/zend-validator/blob/master/src/File/IsImage.php#L44)
can be found in the source code.
Please refer to the [MimeType validator](mime-type.md) for options and public
methods.
## Basic Usage
```php
$validator = new Zend\Validator\File\IsImage();
if ($validator->isValid('./myfile.jpg')) {
// file is valid
}
```

View File

@@ -0,0 +1,68 @@
# Md5
`Zend\Validator\File\Md5` allows you to validate if a given file's hashed
contents matches the supplied md5 hash(es). It is subclassed from the
[Hash validator](hash.md) to provide a validator that supports only the MD5
algorithm.
> ### Requires the hash extension
>
> This validator requires the PHP [Hash extension](http://php.net/hash) PHP with
> the `md5` algorithm.
## Supported Options
The following set of options are supported:
- `hash`: String hash or array of hashes against which to validate.
## Basic Usage
```php
use Zend\Validator\File\Md5;
// Does file have the given hash?
$validator = new Md5('3b3652f336522365223');
// Or, check file against multiple hashes
$validator = new Md5([
'3b3652f336522365223', 'eb3365f3365ddc65365'
]);
// Or use options notation:
$validator = new Md5(['hash' => [
'3b3652f336522365223', 'eb3365f3365ddc65365'
]]);
// Perform validation with file path
if ($validator->isValid('./myfile.txt')) {
// file is valid
}
```
## Public Methods
### getMd5
```php
getMd5() : array
```
Returns an array of MD5 hashes against which to validate.
### addMd5
```php
addMd5(string|array $options) : void
```
Add one or more hashes to validate against.
### setMd5
```php
setMd5(string|array $options) : void
```
Overwrite any previously set hashes with those specified.

View File

@@ -0,0 +1,68 @@
# MimeType
`Zend\Validator\File\MimeType` checks the MIME type of files. It will assert
`true` when a given file matches any defined MIME type.
This validator is inversely related to the
[ExcludeMimeType validator](exclude-mime-type.md)
> ### Compatibility
>
> This component will use the `FileInfo` extension if it is available. If it's
> not, it will degrade to the `mime_content_type()` function. And if the
> function call fails, it will use the MIME type which is given by HTTP. You
> should be aware of possible security problems when you do not have `FileInfo`
> or `mime_content_type()` available; the MIME type given by HTTP is not secure
> and can be easily manipulated.
## Supported Options
The following set of options are supported:
- `mimeType`: Comma-delimited string of MIME types, or array of MIME types,
against which to test. Types can be specific (e.g., `image/jpg`), or refer
only to the group (e.g., `image`).
- `magicFile`: Location of the magicfile to use for MIME type comparisons;
defaults to the value of the `MAGIC` constant.
- `enableHeaderCheck`: Boolean flag indicating whether or not to use HTTP
headers when determining the MIME type if neither the `FileInfo` nor
`mime_magic` extensions are available; defaults to `false`.
## Basic Usage
```php
use Zend\Validator\File\MimeType;
// Only allow 'gif' or 'jpg' files
$validator = new MimeType('image/gif,image/jpg');
// ... or with array notation:
$validator = new MimeType(['image/gif', 'image/jpg']);
// ... or restrict to entire group of types:
$validator = new MimeType(['image', 'audio']);
// Specify a different magicFile:
$validator = new MimeType([
'mimeType' => ['image/gif', 'image/jpg'],
'magicFile' => '/path/to/magicfile.mgx',
]);
// Enable HTTP header scanning (do not do this!):
$validator = new MimeType([
'mimeType' => ['image/gif', 'image/jpg'],
'enableHeaderCheck' => true,
]);
// Perform validation
if ($validator->isValid('./myfile.jpg')) {
// file is valid
}
```
> ### Validating MIME groups is potentially dangerous
>
> Allowing "groups" of MIME types will accept **all** members of this group, even
> if your application does not support them. For instance, When you allow
> `image` you also allow `image/xpixmap` and `image/vasa`, both of which could
> be problematic.

View File

@@ -0,0 +1,42 @@
# NotExists
`Zend\Validator\File\NotExists` checks for the existence of files in specified
directories.
This validator is inversely related to the [Exists validator](exists.md).
## Supported Options
The following set of options are supported:
- `directory`: Array of directories or comma-delimited string of directories
against which to validate.
## Basic Usage
```php
use Zend\Validator\File\NotExists;
// Only allow files that do not exist in ~either~ directories
$validator = new NotExists('/tmp,/var/tmp');
// ... or with array notation:
$validator = new NotExists(['/tmp', '/var/tmp']);
// ... or using options notation:
$validator = new NotExists(['directory' => [
'/tmp',
'/var/tmp',
]]);
// Perform validation
if ($validator->isValid('/home/myfile.txt')) {
// file is valid
}
```
> ### Checks against all directories
>
> This validator checks whether the specified file does not exist in **any** of
> the given directories; validation will fail if the file exists in one (or
> more) of the given directories.

View File

@@ -0,0 +1,69 @@
# Sha1
`Zend\Validator\File\Sha1` allows you to validate if a given file's hashed
contents matches the supplied sha1 hash(es). It is subclassed from the
[Hash validator](hash.md) to provide a validator that only supports the `sha1`
algorithm.
> ### Requires the hash extension
>
> This validator requires the PHP [Hash extension](http://php.net/hash) with the
> `sha1` algorithm.
## Supported Options
The following set of options are supported:
- `hash`: String hash or array of hashes against which to validate.
## Basic Usage
```php
use Zend\Validator\File\Sha1;
// Does file have the given hash?
$validator = new Sha1('3b3652f336522365223');
// Or check file against multiple hashes:
$validator = new Sha1([
'3b3652f336522365223',
'eb3365f3365ddc65365',
]);
// Or using options notation:
$validator = new Sha1(['hash' => [
'3b3652f336522365223',
'eb3365f3365ddc65365',
]]);
// Perform validation with file path
if ($validator->isValid('./myfile.txt')) {
// file is valid
}
```
## Public Methods
### getSha1
```php
getSha1() : array
```
Returns an array of sha1 hashes against which to validate.
### addSha1
```php
addSha1(string|array $options) : void
```
Add one or more hashes to validate against.
### setSha1
```php
setSha1(string|array $options) : void
```
Overwrite any previously set hashes with those specified.

View File

@@ -0,0 +1,37 @@
# Size
`Zend\Validator\File\Size` checks for the size of a file.
## Supported Options
The following set of options are supported:
- `min`: Minimum file size in integer bytes, or in string SI notation; `null`
indicates no minimum required.
- `max`: maximum file size in integer bytes, or in string SI notation; `null`
indicates no maximum required.
- `useByteString`: Boolean flag indicating whether to dispaly error messages
using SI notation (default, `true`), or in bytes (`false`).
SI units supported are: kB, MB, GB, TB, PB, and EB. All sizes are converted
using 1024 as the base value (ie. 1kB == 1024 bytes, 1MB == 1024kB).
## Basic Usage
```php
use Zend\Validator\File\Size;
// Limit the file size to 40000 bytes
$validator = new Size(40000);
// Limit the file size to between 10kB and 4MB
$validator = new Size([
'min' => '10kB',
'max' => '4MB',
]);
// Perform validation with file path
if ($validator->isValid('./myfile.txt')) {
// file is valid
}
```

View File

@@ -0,0 +1,25 @@
# UploadFile
`Zend\Validator\File\UploadFile` checks whether a single file has been uploaded
via a form `POST` and will return descriptive messages for any upload errors.
# Basic Usage
```php
use Zend\Http\PhpEnvironment\Request;
use Zend\Validator\File\UploadFile;
$request = new Request();
$files = $request->getFiles();
// i.e. $files['my-upload']['error'] == 0
$validator = new UploadFile();
if ($validator->isValid($files['my-upload'])) {
// file is valid
}
```
## Usage with zend-inputfilter
When using zend-inputfilter's [FileInput](https://zendframework.github.io/zend-inputfilter/file-input/),
this validator will be automatically prepended to the validator chain.

View File

@@ -0,0 +1,30 @@
# Upload
`Zend\Validator\File\Upload` validates that a file upload operation was
successful.
## Supported Options
`Zend\Validator\File\Upload` supports the following options:
- `files`: array of file uploads. This is generally the `$_FILES` array, but
should be normalized per the details in [PSR-7](http://www.php-fig.org/psr/psr-7/#1-6-uploaded-files)
(which is also how [the zend-http Request](https://zendframework.github.io/zend-http)
normalizes the array).
## Basic Usage
```php
use Zend\Validator\File\Upload;
// Using zend-http's request:
$validator = new Upload($request->getFiles());
// Or using options notation:
$validator = new Upload(['files' => $request->getFiles()]);
// Validate:
if ($validator->isValid('foo')) {
// "foo" file upload was successful
}
```

View File

@@ -0,0 +1,34 @@
# WordCount
`Zend\Validator\File\WordCount` validates that the number of words within a file
match the specified criteria.
## Supported Options
The following set of options are supported:
- `min`: the minimum number of words required; `null` indicates no minimum.
- `max`: the maximum number of words required; `null` indicates no maximum.
## Basic Usage
```php
use Zend\Validator\File\WordCount;
// Limit the amount of words to a maximum of 2000:
$validator = new WordCount(2000);
// Limit the amount of words to between 100 and 5000:
$validator = new WordCount(100, 5000);
// ... or use options notation:
$validator = new WordCount([
'min' => 1000,
'max' => 5000,
]);
// Perform validation with file path
if ($validator->isValid('./myfile.txt')) {
// file is valid
}
```

View File

@@ -0,0 +1,48 @@
# GreaterThan Validator
`Zend\Validator\GreaterThan` allows you to validate if a given value is greater
than a minimum border value.
> ### Only supports numbers
>
> `Zend\Validator\GreaterThan` supports only the validation of numbers. Strings
> or dates can not be validated with this validator.
## Supported options
The following options are supported for `Zend\Validator\GreaterThan`:
- `inclusive`: Defines if the validation is inclusive of the minimum value,
or exclusive. It defaults to `false`.
- `min`: Sets the minimum allowed value.
## Basic usage
To validate if a given value is greater than a defined minimum:
```php
$valid = new Zend\Validator\GreaterThan(['min' => 10]);
$value = 8;
$return = $valid->isValid($value);
// returns false
```
The above example returns `true` for all values which are greater than 10.
## Inclusive validation
Sometimes it is useful to validate a value by including the minimum value.
```php
$valid = new Zend\Validator\GreaterThan([
'min' => 10,
'inclusive' => true,
]);
$value = 10;
$result = $valid->isValid($value);
// returns true
```
The example is identical to our first example, with the exception that we
included the minimum value. Now the value '10' is allowed and will return
`true`.

View File

@@ -0,0 +1,25 @@
# Hex Validator
`Zend\Validator\Hex` allows you to validate if a given value contains only
hexadecimal characters. These are all characters from **0 to 9** and **A to F**,
case insensitive. There is no length limitation for the input you want to
validate.
```php
$validator = new Zend\Validator\Hex();
if ($validator->isValid('123ABC')) {
// value contains only hex chars
} else {
// false
}
```
> ### Invalid characters
>
> All other characters will return false, including whitespace and decimal
> points. Additionally, unicode zeros and numbers from other scripts than latin
> will not be treated as valid.
## Supported options
There are no additional options for `Zend\Validator\Hex`.

View File

@@ -0,0 +1,142 @@
# Hostname Validator
`Zend\Validator\Hostname` allows you to validate a hostname against a set of
known specifications. It is possible to check for three different types of
hostnames: a DNS Hostname (i.e. `domain.com`), IP address (i.e. 1.2.3.4), and
Local hostnames (i.e. localhost). By default, only DNS hostnames are matched.
## Supported options
The following options are supported for `Zend\Validator\Hostname`:
- `allow`: Defines the sort of hostname which is allowed to be used.
[See below](#validating-different-types-of-hostnames) for details.
- `idn`: Defines if IDN domains are allowed or not. This option defaults to
`true`.
- `ip`: Allows defining a custom IP validator. This option defaults to a new
instance of `Zend\Validator\Ip`.
- `tld`: Defines if TLDs are validated. This option defaults to `true`.
## Basic usage
```php
$validator = new Zend\Validator\Hostname();
if ($validator->isValid($hostname)) {
// hostname appears to be valid
} else {
// hostname is invalid; print the reasons
foreach ($validator->getMessages() as $message) {
echo "$message\n";
}
}
```
This will match the hostname `$hostname` and on failure populate `getMessages()`
with useful error messages.
## Validating different types of hostnames
You may find you also want to match IP addresses, Local hostnames, or a
combination of all allowed types. This can be done by passing a parameter to
`Zend\Validator\Hostname` when you instantiate it. The parameter should be an
integer which determines what types of hostnames are allowed. You are encouraged
to use the `Zend\Validator\Hostname` constants to do this.
The `Zend\Validator\Hostname` constants are:
- `ALLOW_DNS`, to allow only DNS hostnames
- `ALLOW_IP` to allow IP addresses
- `ALLOW_LOCAL` to allow local network names
- `ALLOW_URI` to allow [RFC3986](http://tools.ietf.org/html/rfc3986)-compliant addresses
- `ALLOW_ALL` to allow all four above types
> ### Additional Information on `ALLOW_URI`
>
> `ALLOW_URI` allows checking hostnames according to
> [RFC3986](http://tools.ietf.org/html/rfc3986). These are registered names
> which are used by WINS, NetInfo and also local hostnames like those defined
> within your `hosts` file.
To check for IP addresses only, you can use the example below:
```php
use Zend\Validator\Hostname;
$validator = new Hostname(Hostname::ALLOW_IP);
if ($validator->isValid($hostname)) {
// hostname appears to be valid
} else {
// hostname is invalid; print the reasons
foreach ($validator->getMessages() as $message) {
echo "$message\n";
}
}
```
As well as using `ALLOW_ALL` to accept all common hostnames types, you can
combine these types to allow for combinations. For example, to accept DNS and
Local hostnames:
```php
use Zend\Validator\Hostname;
$validator = new Hostname(Hostname::ALLOW_DNS | Hostname::ALLOW_IP);
```
## Validating International Domains Names
Some Country Code Top Level Domains (ccTLDs), such as 'de' (Germany), support
international characters in domain names. These are known as International
Domain Names (IDN). These domains can be matched by `Zend\Validator\Hostname`
via extended characters that are used in the validation process.
At the time of writing, more than 50 ccTLDs support IDN domains.
The `Hostname` validator matches IDN domains by default. If you wish to disable
IDN validation, either pass a parameter to the `Zend\Validator\Hostname`
constructor or call the `setValidateIdn()` method.
You can disable IDN validation by passing a second parameter to the
`Zend\Validator\Hostname` constructor in the following way.
```php
$validator = new Zend\Validator\Hostname([
'allow' => Zend\Validator\Hostname::ALLOW_DNS,
'useIdnCheck' => false,
]);
```
Alternatively you can either pass `true` or `false` to `setValidateIdn()` to
enable or disable IDN validation. If you are trying to match an IDN hostname
which isn't currently supported, it is likely it will fail validation if it has
any international characters in it. Where a ccTLD file doesn't exist in
`Zend/Validator/Hostname` specifying the additional characters, a normal hostname
validation is performed.
Please note that IDNs are only validated if you allow DNS hostnames to be
validated.
## Validating Top Level Domains
By default, a hostname will be verified against a list of known TLDs. If this
functionality is not required, it can be disabled in much the same way as
disabling IDN support. You can disable TLD validation by passing a third
parameter to the `Zend\Validator\Hostname` constructor. In the example below we
are supporting IDN validation via the second parameter.
```php
use Zend\Validator\Hostname;
$validator = new Hostname([
'allow' => Hostname::ALLOW_DNS,
'useIdnCheck' => true,
'useTldCheck' => false,
]);
```
Alternatively you can either pass `true` or `false` to `setValidateTld()` to
enable or disable TLD validation.
Please note, TLDs are only validated if you allow DNS hostnames to be validated.

View File

@@ -0,0 +1,55 @@
# Iban Validator
`Zend\Validator\Iban` validates if a given value could be a IBAN number. IBAN is
the abbreviation for "International Bank Account Number".
## Supported options
The following options are supported for `Zend\Validator\Iban`:
- `country_code`: Sets the country code which is used to get the IBAN format
for validation.
## IBAN validation
IBAN numbers are always related to a country. This means that different
countries use different formats for their IBAN numbers. This is the reason why
IBAN numbers always need a country code. By knowing this we already know how
to use `Zend\Validator\Iban`.
### Ungreedy IBAN validation
Sometime it is useful just to validate if the given value is a IBAN number or
not. This means that you don't want to validate it against a defined country.
This can be done by using `false` as locale.
```php
$validator = new Zend\Validator\Iban(['country_code' => false]);
// Note: you can also provide FALSE as the sole parameter
if ($validator->isValid('AT611904300234573201')) {
// IBAN appears to be valid
} else {
// IBAN is not valid
}
```
In this situation, any IBAN number from any country will considered valid. Note
that this should not be done when you accept only accounts from a single
country!
### Region aware IBAN validation
To validate against a defined country, you just provide a country code. You can
do this during instaniation via the option `country_code`, or afterwards by
using `setCountryCode()`.
```php
$validator = new Zend\Validator\Iban(['country_code' => 'AT']);
if ($validator->isValid('AT611904300234573201')) {
// IBAN appears to be valid
} else {
// IBAN is not valid
}
```

View File

@@ -0,0 +1,239 @@
# Identical Validator
`Zend\Validator\Identical` allows you to validate if a given value is identical
with a set token.
## Supported options
The following options are supported for `Zend\Validator\Identical`:
- `strict`: Defines if the validation should be strict (i.e., if types should
also be considered). The default value is `true`.
- `token`: Sets the token against which the input will be validated.
- `literal`: If set to `true`, the validation will skip the lookup for elements
in the form context, and validate the token just the way it was provided. The
default value is `false`.
## Basic usage
To validate if two values are identical, you need to set the original value as
the token, as demonstrated in the following example:
token.
```php
$valid = new Zend\Validator\Identical('origin');
if ($valid->isValid($value)) {
return true;
}
```
The validation will only then return `true` when both values are 100% identical.
In our example, when `$value` is `'origin'`.
You can set the token after instantiation by using the method `setToken()`.
## Identical objects
`Zend\Validator\Identical` can validate not only strings, but any other variable
type, such as booleans, integers, floats, arrays, or even objects. As already
noted, the token and value must be identical.
```php
$valid = new Zend\Validator\Identical(123);
if ($valid->isValid($input)) {
// input appears to be valid
} else {
// input is invalid
}
```
> ### Type comparison
>
> You should be aware of the variable type used for validation. This means that
> the string `'3'` is not identical to integer `3`. When you want non-strict
> validation, you must set the `strict` option to `false`.
## Form elements
`Zend\Validator\Identical` supports the comparison of form elements. This can be
done by using the element's name as the `token`:
```php
$form->add([
'name' => 'elementOne',
'type' => 'Password',
]);
$form->add([
'name' => 'elementTwo',
'type' => 'Password',
'validators' => array(
[
'name' => 'Identical',
'options' => [
'token' => 'elementOne',
],
],
],
]);
```
By using the element's name from the first element as the `token` for the second
element, the validator validates if the second element is equal with the first
element. In the case your user does not enter two identical values, you will get
a validation error.
### Validating a Value From a Fieldset
Sometimes you will need to validate an input that lives inside a fieldset, and
this can be accomplished as follows:
```php
use Zend\Form\Element;
use Zend\Form\Fieldset;
use Zend\Form\Form;
use Zend\InputFilter\Input;
use Zend\InputFilter\InputFilter;
$userFieldset = new Fieldset('user'); // (1)
$userFieldset->add([
'name' => 'email', // (2)
'type' => 'Email',
]);
// Let's add one fieldset inside the 'user' fieldset,
// so we can see how to manage the token in a different deepness
$deeperFieldset = new Fieldset('deeperFieldset'); // (3)
$deeperFieldset->add([
'name' => 'deeperFieldsetInput', // (4)
'type' => 'Text',
'options' => [
'label' => 'What validator are we testing?',
],
]);
$userFieldset->add($deeperFieldset);
$signUpForm = new Form('signUp');
$signUpForm->add($userFieldset);
// Add an input that will validate the 'email' input from 'user' fieldset
$signUpForm->add([
'name' => 'confirmEmail', // (5)
'type' => 'Email',
]);
// Add an input that will validate the 'deeperFieldsetInput' from
// 'deeperFieldset' that lives inside the 'user' fieldset
$signUpForm->add([
'name' => 'confirmTestingValidator', // (6)
'type' => 'Text',
]);
// This will ensure the user enter the same email in 'email' (2) and
// 'confirmEmail' (5)
$inputFilter = new InputFilter();
$inputFilter->add([
'name' => 'confirmEmail', // references (5)
'validators' => [
array(
'name' => 'Identical',
'options' => [
// 'user' key references 'user' fieldset (1), and 'email'
// references 'email' element inside 'user' fieldset (2)
'token' => ['user' => 'email'],
],
],
],
]);
// This will ensure the user enter the same string in 'deeperFieldsetInput' (4)
// and 'confirmTestingValidator' (6)
$inputFilter->add([
'name' => 'confirmTestingValidator', // references (6)
'validators' => [
[
'name' => 'Identical',
'options' => [
'token' => [
'user' => [ // references 'user' fieldset (1)
// 'deeperFieldset' key references 'deeperFieldset'
// fieldset (3); 'deeperFieldsetInput' references
// 'deeperFieldsetInput' element (4)
'deeperFieldset' => 'deeperFieldsetInput',
],
],
],
],
],
]);
$signUpForm->setInputFilter($inputFilter);
```
> #### Use one token per leaf
>
> Aways make sure that your token array have just one key per level all the way
> till the leaf, otherwise you can end up with unexpected results.
## Strict validation
As mentioned before, `Zend\Validator\Identical` validates tokens using strict
typing. You can change this behaviour by using the `strict` option. The default
value for this property is `true`.
```php
$valid = new Zend\Validator\Identical(['token' => 123, 'strict' => false]);
$input = '123';
if ($valid->isValid($input)) {
// input appears to be valid
} else {
// input is invalid
}
```
The difference to the previous example is that the validation returns in this
case `true`, even if you compare a integer with string value as long as the
content is identical but not the type.
For convenience you can also use `setStrict()` and `getStrict()`.
## Configuration
As all other validators, `Zend\Validator\Identical` also supports the usage of
configuration settings during instantiation. This means that you can configure
this validator with a `Traversable` object.
There is a case which you should be aware of. If you are using an array as
token, and it contains a `token` key, you should wrap it within another
`token` key. See the examples below to undestand this situation.
```php
// This will not validate ['token' => 123], it will actually validate the
// integer 123
$valid = new Zend\Validator\Identical(['token' => 123]);
if ($valid->isValid($input)) {
// input appears to be valid
} else {
// input is invalid
}
```
The reason for this special case is that you can configure the token which has
to be used by giving the `token` key.
So, when you are using an array as the token, and it contains one element with a
`token` key, then you have to wrap it as shown in the example below:
```php
// Unlike the previous example, this will validate ['token' => 123]
$valid = new Zend\Validator\Identical(['token' => ['token' => 123]]);
if ($valid->isValid($input)) {
// input appears to be valid
} else {
// input is invalid
}
```
If the array you are willing to validate does not have a `token` key, you do not
need to wrap it.

View File

@@ -0,0 +1,161 @@
# InArray Validator
`Zend\Validator\InArray` allows you to validate if a given value is contained
within an array. It is also able to validate multidimensional arrays.
## Supported options
The following options are supported for `Zend\Validator\InArray`:
- `haystack`: Sets the haystack for the validation. `recursive`: Defines if the
- validation should be done recursively. This option
defaults to `false`.
- `strict`: Three modes of comparison are offered owing to an often overlooked,
and potentially dangerous security issue when validating string input from
user input.
- `InArray::COMPARE_STRICT`: This is a normal `in_array()` strict comparison
that checks value and type.
- `InArray::COMPARE_NOT_STRICT`: This is a normal `in_array()` non-strict
comparison that checks value only, but not type.
- `InArray::COMPARE_NOT_STRICT_AND_PREVENT_STR_TO_INT_VULNERABILTY`: This
operates in essentially the same way as `InArray::COMPARE_NOT_STRICT`,
but ensures that strings are not cast to integer during comparison,
preventing `0 == 'foo43'` types of false positives.
> ### Use non-strict carefully
>
> Non-strict mode (`InArray::COMPARE_NOT_STRICT`) may give false positives when
> strings are compared against ints or floats owing to `in_array()`'s behaviour
> of converting strings to int in such cases. Therefore, `'foo'` would become
> `0`, `'43foo'` would become `43`, while `foo43'` would also become `0`.
## Array validation
Basic usage is to provide an array during instantiation:
```php
$validator = new Zend\Validator\InArray([
'haystack' => ['value1', 'value2',...'valueN']
]);
if ($validator->isValid('value')) {
// value found
} else {
// no value found
}
```
This will behave exactly like PHP's `in_array()` method when passed only a
needle and haystack.
> ### Non-strict by default
>
> By default, this validation is not strict, nor can it validate
> multidimensional arrays.
Alternately, you can define the array to validate against after object
construction by using the `setHaystack()` method. `getHaystack()` returns the
actual set haystack array.
```php
$validator = new Zend\Validator\InArray();
$validator->setHaystack(['value1', 'value2',...'valueN']);
if ($validator->isValid('value')) {
// value found
} else {
// no value found
}
```
## Array validation modes
As previously mentioned, there are possible security issues when using the
default non-strict comparison mode, so rather than restricting the developer,
we've chosen to offer both strict and non-strict comparisons, and add a safer
middle-ground.
It's possible to set the strict mode at initialisation and afterwards with the
`setStrict` method. `InArray::COMPARE_STRICT` equates to `true` and
`InArray::COMPARE_NOT_STRICT_AND_PREVENT_STR_TO_INT_VULNERABILITY` equates to
`false`.
```php
// defaults to InArray::COMPARE_NOT_STRICT_AND_PREVENT_STR_TO_INT_VULNERABILITY
$validator = new Zend\Validator\InArray([
'haystack' => array('value1', 'value2', /* ... */ 'valueN'),
]);
// set strict mode
$validator = new Zend\Validator\InArray([
'haystack' => ['value1', 'value2', /* ... */ 'valueN'],
'strict' => InArray::COMPARE_STRICT, // equates to ``true``
]);
// set non-strict mode
$validator = new Zend\Validator\InArray([
'haystack' => ['value1', 'value2', /* ... */ 'valueN'],
'strict' => InArray:COMPARE_NOT_STRICT, // equates to ``false``
]);
// or
$validator->setStrict(InArray::COMPARE_STRICT);
$validator->setStrict(InArray::COMPARE_NOT_STRICT);
$validator->setStrict(InArray::COMPARE_NOT_STRICT_AND_PREVENT_STR_TO_INT_VULNERABILITY);
```
> ### Non-strict safe-mode by default
>
> Note that the `strict` setting is per default `false`.
## Recursive array validation
In addition to PHP's `in_array()` method, this validator can also be used to
validate multidimensional arrays.
To validate multidimensional arrays you have to set the `recursive` option.
```php
$validator = new Zend\Validator\InArray([
'haystack' => array(
'firstDimension' => ['value1', 'value2', / ... */ 'valueN'],
'secondDimension' => ['foo1', 'foo2', /* ... */ 'fooN'],
],
'recursive' => true,
]);
if ($validator->isValid('value')) {
// value found
} else {
// no value found
}
```
Your array will then be validated recursively to see if the given value is
contained. Additionally you could use `setRecursive()` to set this option
afterwards and `getRecursive()` to retrieve it.
```php
$validator = new Zend\Validator\InArray([
'firstDimension' => ['value1', 'value2', /* ... */ 'valueN'],
'secondDimension' => ['foo1', 'foo2', /* ... */ 'fooN'],
]);
$validator->setRecursive(true);
if ($validator->isValid('value')) {
// value found
} else {
// no value found
}
```
> ### Default setting for recursion
>
> By default, the recursive validation is turned off.
> ### Option keys within the haystack
>
> When you are using the keys `haystack`, `strict`, or `recursive` within
> your haystack, then you must wrap the `haystack` key.

View File

@@ -0,0 +1,66 @@
# Ip Validator
`Zend\Validator\Ip` allows you to validate if a given value is an IP address. It
supports the IPv4, IPv6, and IPvFuture definitions.
## Supported options
The following options are supported for `Zend\Validator\Ip`:
- `allowipv4`: Defines if the validator allows IPv4 addresses. This option
defaults to `true`.
- `allowipv6`: Defines if the validator allows IPv6 addresses. This option
defaults to `true`.
- `allowipvfuture`: Defines if the validator allows IPvFuture addresses. This
option defaults to `false`.
- `allowliteral`: Defines if the validator allows IPv6 or IPvFuture with URI
literal style (the IP surrounded by brackets). This option defaults to `true`.
## Basic usage
```php
$validator = new Zend\Validator\Ip();
if ($validator->isValid($ip)) {
// ip appears to be valid
} else {
// ip is invalid; print the reasons
}
```
> ### Invalid IP addresses
>
> Keep in mind that `Zend\Validator\Ip` only validates IP addresses. Addresses
> like '`mydomain.com`' or '`192.168.50.1/index.html`' are not valid IP
> addresses. They are either hostnames or valid URLs but not IP addresses.
> ### IPv6/IPvFuture validation
>
> `Zend\Validator\Ip` validates IPv6/IPvFuture addresses using a regex. The
> reason is that the filters and methods from PHP itself don't follow the RFC.
> Many other available classes also don't follow it.
## Validate IPv4 or IPV6 alone
Sometimes it's useful to validate only one of the supported formats; e.g., when
your network only supports IPv4. In this case it would be useless to allow IPv6
within this validator.
To limit `Zend\Validator\Ip` to one protocol, you can set the options `allowipv4`
or `allowipv6` to `false`. You can do this either by giving the option to the
constructor or by using `setOptions()` afterwards.
```php
$validator = new Zend\Validator\Ip(['allowipv6' => false]);
if ($validator->isValid($ip)) {
// ip appears to be valid ipv4 address
} else {
// ip is not an ipv4 address
}
```
> ### Default behaviour
>
> The default behaviour which `Zend\Validator\Ip` follows is to allow both
> standards.

View File

@@ -0,0 +1,86 @@
# Isbn Validator
`Zend\Validator\Isbn` allows you to validate an ISBN-10 or ISBN-13 value.
## Supported options
The following options are supported for `Zend\Validator\Isbn`:
- `separator`: Defines the allowed separator for the ISBN number. It defaults to
an empty string.
- `type`: Defines the allowed ISBN types. It defaults to
`Zend\Validator\Isbn::AUTO`. For details, take a look at the section on
[explicit types](#setting-an-explicit-isbn-validation-type).
## Basic usage
A basic example of usage is below:
```php
$validator = new Zend\Validator\Isbn();
if ($validator->isValid($isbn)) {
// isbn is valid
} else {
// isbn is not valid
}
```
This will validate any ISBN-10 and ISBN-13 without separator.
## Setting an explicit ISBN validation type
An example of an ISBN type restriction follows:
```php
use Zend\Validator\Isbn;
$validator = new Isbn();
$validator->setType(Isbn::ISBN13);
// OR
$validator = new Isbn([ 'type' => Isbn::ISBN13]);
if ($validator->isValid($isbn)) {
// this is a valid ISBN-13 value
} else {
// this is an invalid ISBN-13 value
}
```
The above will validate only ISBN-13 values.
Valid types include:
- `Zend\Validator\Isbn::AUTO` (default)
- `Zend\Validator\Isbn::ISBN10`
- `Zend\Validator\Isbn::ISBN13`
## Specifying a separator restriction
An example of separator restriction:
```php
$validator = new Zend\Validator\Isbn();
$validator->setSeparator('-');
// OR
$validator = new Zend\Validator\Isbn(['separator' => '-']);
if ($validator->isValid($isbn)) {
// this is a valid ISBN with separator
} else {
// this is an invalid ISBN with separator
}
```
> ### Values without separators
>
> This will return `false` if `$isbn` doesn't contain a separator **or** if it's
> an invalid *ISBN* value.
Valid separators include:
- `` (empty) (default)
- `-` (hyphen)
- ` ` (space)

View File

@@ -0,0 +1,43 @@
# IsInstanceOf Validator
`Zend\Validator\IsInstanceOf` allows you to validate whether a given object is
an instance of a specific class or interface.
## Supported options
The following options are supported for `Zend\Validator\IsInstanceOf`:
- `className`: Defines the fully-qualified class name which objects must be an
instance of.
## Basic usage
```php
$validator = new Zend\Validator\IsInstanceOf([
'className' => 'Zend\Validator\Digits'
]);
$object = new Zend\Validator\Digits();
if ($validator->isValid($object)) {
// $object is an instance of Zend\Validator\Digits
} else {
// false. You can use $validator->getMessages() to retrieve error messages
}
```
If a string argument is passed to the constructor of
`Zend\Validator\IsInstanceOf`, then that value will be used as the class name:
```php
use Zend\Validator\Digits;
use Zend\Validator\IsInstanceOf;
$validator = new IsInstanceOf(Digits::class);
$object = new Digits();
if ($validator->isValid($object)) {
// $object is an instance of Zend\Validator\Digits
} else {
// false. You can use $validator->getMessages() to retrieve error messages
}
```

View File

@@ -0,0 +1,48 @@
# LessThan Validator
`Zend\Validator\LessThan` allows you to validate if a given value is less than a
maximum value.
> Supports only number validation
>
> `Zend\Validator\LessThan` supports only the validation of numbers. Strings or
> dates can not be validated with this validator.
## Supported options
The following options are supported for `Zend\Validator\LessThan`:
- `inclusive`: Defines if the validation is inclusive the maximum value or
exclusive. It defaults to `false`.
- `max`: Sets the maximum allowed value.
## Basic usage
To validate if a given value is less than a defined maximum:
```php
$valid = new Zend\Validator\LessThan(['max' => 10]);
$value = 12;
$return = $valid->isValid($value);
// returns false
```
The above example returns `true` for all values lower than 10.
## Inclusive validation
Sometimes it is useful to validate a value by including the maximum value:
```php
$valid = new Zend\Validator\LessThan([
'max' => 10,
'inclusive' => true,
]);
$value = 10;
$result = $valid->isValid($value);
// returns true
```
The example is identical to our first example, with the exception that we've
specified that the maximum is inclusive. Now the value '10' is allowed and will
return `true`.

View File

@@ -0,0 +1,80 @@
# NotEmpty Validator
This validator allows you to validate if a given value is not empty. This is
often useful when working with form elements or other user input, where you can
use it to ensure required elements have values associated with them.
## Supported options
The following options are supported for `Zend\Validator\NotEmpty`:
- `type`: Sets the type of validation which will be processed; for details, see
the section on [specifying empty behavior](#specifying-empty-behavior).
## Default behaviour
By default, this validator works differently than you would expect when you've
worked with PHP's `empty()` operator. In particular, this validator will
evaluate both the integer `0` and string `'0'` as empty.
```php
$valid = new Zend\Validator\NotEmpty();
$value = '';
$result = $valid->isValid($value);
// returns false
```
## Specifying empty behavior
Some projects have differing opinions of what is considered an "empty" value: a
string with only whitespace might be considered empty, or `0` may be
considered non-empty (particularly for boolean sequences). To accommodate
differing needs, `Zend\Validator\NotEmpty` allows you to configure which types
should be validated as empty and which not.
The following types can be handled:
- `boolean`: Returns `false` when the boolean value is `false`.
- `integer`: Returns `false` when an integer `0` value is given. By default,
this validation is not activate and returns `true` for any integer values.
- `float`: Returns `false` when a float `0.0` value is given. By default, this
validation is not activate and returns `true` on any float values.
- `string`: Returns `false` when an empty string `''` is given.
- `zero`: Returns `false` when the single character zero (`'0'`) is given.
- `empty_array`: Returns `false` when an empty `array` is given.
- `null`: Returns `false` when a `null` value is given.
- `php`: Returns `false` on wherever PHP's `empty()` would return `true`.
- `space`: Returns `false` when an string is given which contains only
whitespace.
- `object`: Returns `true`. `false` will be returned when `object` is not
allowed but an object is given.
- `object_string`: Returns `false` when an object is given and its
`__toString()` method returns an empty string.
- `object_count`: Returns `false` when an object is given, it implements
`Countable`, and its count is 0.
- `all`: Returns `false` on all above types.
All other given values will return `true` per default.
There are several ways to select which of the above types are validated. You can
give one or multiple types and add them, you can provide an array, you can use
constants, or you can provide a textual string. See the following examples:
```php
use Zend\Validator\NotEmpty;
// Returns false on 0
$validator = new NotEmpty(NotEmpty::INTEGER);
// Returns false on 0 or '0'
$validator = new NotEmpty( NotEmpty::INTEGER + NotEmpty::ZERO);
// Returns false on 0 or '0'
$validator = new NotEmpty([ NotEmpty::INTEGER, NotEmpty::ZERO ]);
// Returns false on 0 or '0'
$validator = new NotEmpty(['integer', 'zero']);
```
You can also provide an instance of `Traversable` to set the desired types. To
set types after instantiation, use the `setType()` method.

View File

@@ -0,0 +1,90 @@
# PostCode Validator
`Zend\I18n\Validator\PostCode` allows you to determine if a given value is a
valid postal code. Postal codes are specific to cities, and in some locales
termed ZIP codes.
`Zend\I18n\Validator\PostCode` knows more than 160 different postal code
formats. To select the correct format there are two ways. You can either use a
fully qualified locale, or you can set your own format manually.
## Supported options
The following options are supported for `Zend\I18n\Validator\PostCode`:
- `format`: Sets a postcode format which will be used for validation of the
input.
- `locale`: Sets a locale from which the postcode will be taken from.
## Usage
Using a locale is more convenient as zend-validator already knows the
appropriate postal code format for each locale; however, you need to use the
fully qualified locale (one containing a region specifier) to do so. For
instance, the locale `de` is a locale but could not be used with
`Zend\I18n\Validator\PostCode` as it does not include the region; `de_AT`,
however, would be a valid locale, as it specifies the region code (`AT`, for
Austria).
```php
$validator = new Zend\I18n\Validator\PostCode('de_AT');
```
When you don't set a locale yourself, then `Zend\I18n\Validator\PostCode` will
use the application wide set locale, or, when there is none, the locale returned
by `Locale`.
```php
// application wide locale within your bootstrap
Locale::setDefault('de_AT');
$validator = new Zend\I18n\Validator\PostCode();
```
You can also change the locale afterwards by calling `setLocale()`. And of
course you can get the actual used locale by calling `getLocale()`.
```php
$validator = new Zend\I18n\Validator\PostCode('de_AT');
$validator->setLocale('en_GB');
```
Postal code formats are regular expression strings. When the international
postal code format, which is used by setting the locale, does not fit your
needs, then you can also manually set a format by calling `setFormat()`.
```php
$validator = new Zend\I18n\Validator\PostCode('de_AT');
$validator->setFormat('AT-\d{5}');
```
> ### Conventions for self defined formats
>
> When using self defined formats, you should omit the regex delimiters and
> anchors (`'/^'` and `'$/'`). They are attached automatically.
>
> You should also be aware that postcode values are always be validated in a
> strict way. This means that they have to be written standalone without
> additional characters when they are not covered by the format.
## Constructor options
At its most basic, you may pass a string representing a fully qualified locale
to the constructor of `Zend\I18n\Validator\PostCode`.
```php
$validator = new Zend\I18n\Validator\PostCode('de_AT');
$validator = new Zend\I18n\Validator\PostCode($locale);
```
Additionally, you may pass either an array or a `Traversable` instance to the
constructor. When you do so, you must include either the key `locale` or
`format`; these will be used to set the appropriate values in the validator
object.
```php
$validator = new Zend\I18n\Validator\PostCode([
'locale' => 'de_AT',
'format' => 'AT_\d+'
]);
```

View File

@@ -0,0 +1,41 @@
# Regex Validator
This validator allows you to validate if a given string conforms a defined
regular expression.
## Supported options
The following options are supported for `Zend\Validator\Regex`:
- `pattern`: Sets the regular expression pattern for this validator.
## Usage
Validation with regular expressions allows complex validations
without writing a custom validator.
```php
$validator = new Zend\Validator\Regex(['pattern' => '/^Test/']);
$validator->isValid("Test"); // returns true
$validator->isValid("Testing"); // returns true
$validator->isValid("Pest"); // returns false
```
The pattern uses the same syntax as `preg_match()`. For details about regular
expressions take a look into [PHP's manual about PCRE pattern
syntax](http://php.net/reference.pcre.pattern.syntax).
## Pattern handling
It is also possible to set a different pattern afterwards by using
`setPattern()` and to get the actual set pattern with `getPattern()`.
```php
$validator = new Zend\Validator\Regex(['pattern' => '/^Test/']);
$validator->setPattern('ing$/');
$validator->isValid("Test"); // returns false
$validator->isValid("Testing"); // returns true
$validator->isValid("Pest"); // returns false
```

View File

@@ -0,0 +1,70 @@
# Sitemap Validators
The following validators conform to the
[Sitemap XML protocol](http://www.sitemaps.org/protocol.php).
## Supported options
There are no additional supported options for any of the `Sitemap` validators.
## Changefreq
`Zend\Validator\Sitemap\Changefreq` validates whether a string is valid for
using as a 'changefreq' element in a Sitemap XML document. Valid values are:
'always', 'hourly', 'daily', 'weekly', 'monthly', 'yearly', or 'never'.
Returns `true` if and only if the value is a string and is equal to one of the
frequencies specified above.
## Sitemap\\Lastmod
`Zend\Validator\Sitemap\Lastmod` validates whether a string is valid for using
as a 'lastmod' element in a Sitemap XML document. The lastmod element should
contain a W3C date string, optionally discarding information about time.
Returns `true` if and only if the given value is a string and is valid according
to the protocol.
```php
$validator = new Zend\Validator\Sitemap\Lastmod();
$validator->isValid('1999-11-11T22:23:52-02:00'); // true
$validator->isValid('2008-05-12T00:42:52+02:00'); // true
$validator->isValid('1999-11-11'); // true
$validator->isValid('2008-05-12'); // true
$validator->isValid('1999-11-11t22:23:52-02:00'); // false
$validator->isValid('2008-05-12T00:42:60+02:00'); // false
$validator->isValid('1999-13-11'); // false
$validator->isValid('2008-05-32'); // false
$validator->isValid('yesterday'); // false
```
## Loc
`Zend\Validator\Sitemap\Loc` validates whether a string is valid for using as a
'loc' element in a Sitemap XML document. This uses
[Zend\\Uri\\Uri::isValid()](https://zendframework.github.io/zend-uri/usage/#validating-the-uri)
internally.
## Priority
`Zend\Validator\Sitemap\Priority` validates whether a value is valid for using
as a 'priority' element in a Sitemap XML document. The value should be a decimal
between 0.0 and 1.0. This validator accepts both numeric values and string
values.
```php
$validator = new Zend\Validator\Sitemap\Priority();
$validator->isValid('0.1'); // true
$validator->isValid('0.789'); // true
$validator->isValid(0.8); // true
$validator->isValid(1.0); // true
$validator->isValid('1.1'); // false
$validator->isValid('-0.4'); // false
$validator->isValid(1.00001); // false
$validator->isValid(0xFF); // false
$validator->isValid('foo'); // false
```

View File

@@ -0,0 +1,41 @@
# Step Validator
`Zend\Validator\Step` allows you to validate if a given value is a valid step
value. This validator requires the value to be a numeric value (either string,
int or float).
## Supported options
The following options are supported for `Zend\Validator\Step`:
- `baseValue`: This is the base value from which the step should be computed.
This option defaults to `0`
- `step`: This is the step value. This option defaults to `1`
## Basic usage
```php
$validator = new Zend\Validator\Step();
if ($validator->isValid(1)) {
// value is a valid step value
} else {
// false
}
```
## Using floating-point values
The `Step` validator also supports floating-point base and step values:
```php
$validator = new Zend\Validator\Step([
'baseValue' => 1.1,
'step' => 2.2,
]);
echo $validator->isValid(1.1); // prints true
echo $validator->isValid(3.3); // prints true
echo $validator->isValid(3.35); // prints false
echo $validator->isValid(2.2); // prints false
```

View File

@@ -0,0 +1,118 @@
# StringLength Validator
This validator allows you to validate if a given string is between a defined
length.
> Supports only string validation
>
> `Zend\Validator\StringLength` supports only the validation of strings.
> Integers, floats, dates or objects can not be validated with this validator.
## Supported options
The following options are supported for `Zend\Validator\StringLength`:
- `encoding`: Sets the `ICONV` encoding to use with the string.
- `min`: Sets the minimum allowed length for a string.
- `max`: Sets the maximum allowed length for a string.
## Default behaviour
By default, this validator checks if a value is between `min` and `max` using a
default`min` value of `0` and default `max` value of `NULL` (meaning unlimited).
As such, without any options, the validator only checks that the input is a
string.
## Limiting the maximum string length
To limit the maximum allowed length of a string you need to set the `max`
property. It accepts an integer value as input.
```php
$validator = new Zend\Validator\StringLength(['max' => 6]);
$validator->isValid("Test"); // returns true
$validator->isValid("Testing"); // returns false
```
You can set the maximum allowed length after instantiation by using the
`setMax()` method; `getMax()` retrieves the value.
```php
$validator = new Zend\Validator\StringLength();
$validator->setMax(6);
$validator->isValid("Test"); // returns true
$validator->isValid("Testing"); // returns false
```
## Limiting the minimum string length
To limit the minimal required string length, set the `min`
property using an integer value:
```php
$validator = new Zend\Validator\StringLength(['min' => 5]);
$validator->isValid("Test"); // returns false
$validator->isValid("Testing"); // returns true
```
You can set the value after instantiation using the `setMin()`
method; `getMin()` retrieves the value.
```php
$validator = new Zend\Validator\StringLength();
$validator->setMin(5);
$validator->isValid("Test"); // returns false
$validator->isValid("Testing"); // returns true
```
## Limiting both minimum and maximum string length
Sometimes you will need to set both a minimum and a maximum string length;
as an example, in a username input, you may want to limit the name to a maximum
of 30 characters, but require at least three charcters:
```php
$validator = new Zend\Validator\StringLength(['min' => 3, 'max' => 30]);
$validator->isValid("."); // returns false
$validator->isValid("Test"); // returns true
$validator->isValid("Testing"); // returns true
```
> ### Setting a maximum lower than the minimum
>
> When you try to set a lower maximum value than the specified minimum value, or
> a higher minimum value as the actual maximum value, the validator will raise
> an exception.
## Encoding of values
Strings are always using a encoding. Even when you don't set the encoding
explicitly, PHP uses one. When your application is using a different encoding
than PHP itself, you should set an encoding manually.
You can set an encoding at instantiation with the `encoding` option, or by using
the `setEncoding()` method. We assume that your installation uses ISO and your
application it set to ISO. In this case you will see the below behaviour.
```php
$validator = new Zend\Validator\StringLength(['min' => 6]);
$validator->isValid("Ärger"); // returns false
$validator->setEncoding("UTF-8");
$validator->isValid("Ärger"); // returns true
$validator2 = new Zend\Validator\StringLength([
'min' => 6,
'encoding' => 'UTF-8',
]);
$validator2->isValid("Ärger"); // returns true
```
When your installation and your application are using different encodings, then
you should always set an encoding manually.

View File

@@ -0,0 +1,37 @@
# Timezone Validator
`Zend\Validator\Timezone` allows validating if an input string represents a
timezone.
## Supported validation types
The `Zend\Validator\Timezone` validator is capable of validating the
abbreviation (e.g. `ewt`) as well as the location string (e.g.
`America/Los_Angeles`). These options are stored in the validator as
`LOCATION`, `ABBREVIATION`, and `ALL` class constants.
## Basic Usage
The default validation type will check against abbreviations as well as the
location string.
```php
$validator = new Zend\Validator\Timezone();
$validator->isValid('America/Los_Angeles'); // returns true
$validator->isValid('ewt'); // returns true
$validator->isValid('Foobar'); // returns false
```
To validate against only the location string you can set the type:
```php
use Zend\Validator\Timezone;
$validator = new Timezone();
$validator->setType(Timezone::LOCATION);
$validator->isValid('America/Los_Angeles'); // returns true
$validator->isValid('ewt'); // returns false
$validator->isValid('Foobar'); // returns false
```

View File

@@ -0,0 +1,30 @@
# Uri Validator
`Zend\Validator\Uri` allows you to validate a URI using the `Zend\Uri\Uri`
handler to parse the URI. The validator allows for both validation of absolute
and/or relative URIs. There is the possibility to exchange the handler for
another one in case the parsing of the uri should be done differently.
## Supported options
The following options are supported for `Zend\Validator\Uri`:
- `uriHandler`: Defines the handler to be used to parse the uri. This options
defaults to a new instance of `Zend\Uri\Uri`.
- `allowRelative`: Defines if relative paths are allowed. This option defaults
to `true`.
- `allowAbsolute`: Defines if absolute paths are allowed. This option defaults
to `true`.
## Basic usage
```php
$validator = new Zend\Validator\Uri();
$uri = 'http://framework.zend.com/manual';
if ($validator->isValid($uri)) {
// $uri was valid
} else {
// false. You can use $validator->getMessages() to retrieve error messages
}
```

View File

@@ -0,0 +1,38 @@
# UUID Validator
`Zend\Validator\Uuid` allows validating [Universally Unique IDentifiers](https://en.wikipedia.org/wiki/Universally_unique_identifier)
(UUIDs). UUIDs are 128-bit values that are guaranteed to be "practically unique"
in order to help prevent identifier conflicts. Five separate UUID versions
exist:
- Version 1, which uses a combination of date-time and hardware MAC addresses to
generate the hash.
- Version 2, which uses a combination of date-time and system user/group identifiers.
- Version 3, which uses an MD5sum of a URI or distinguished name to generate the
hash.
- Version 4, which uses a CSPRNG to generate the hash.
- Version 5, which uses the same idea as Version 3, but using SHA-1 for hashing.
The `Uuid` validator is capable of validating whether a string is a valid UUID
of any version. It does not validate that the UUID exists in your system,
however, only that it is well-formed.
> ### Introduced in 2.8.0
>
> `Zend\Validator\Uuid` was introduced with version 2.8.0.
## Supported options
The `Uuid` validator has no additional options.
## Basic usage
```php
$validator = new Zend\Validator\Uuid();
if ($validator->isValid($uuid)) {
// UUID was valid
} else {
// Invalid/mal-formed UUID; use $validator->getMessages() for more detail
}
```

View File

@@ -0,0 +1,222 @@
# Writing Validators
zend-validator supplies a set of commonly needed validators, but many
applications have needs for custom validators. The component allows this via
implementations of `Zend\Validator\ValidatorInterface`.
`Zend\Validator\ValidatorInterface` defines two methods: `isValid()` and
`getMessages()`. An object that implements the interface may be added to a
validator chain using `Zend\Validator\ValidatorChain::addValidator()`. Such
objects may also be used with
[zend-inputfilter](https://zendframework.github.io/zend-inputfilter).
Validators will return a boolean value from `isValid()`, and report information
regarding **why** a value failed validation via `getMessages()`. The
availability of the reasons for validation failures may be valuable to an
application for various purposes, such as providing statistics for usability
analysis.
Basic validation failure message functionality is implemented in
`Zend\Validator\AbstractValidator`, which you may extend for your custom
validators. Extending class you would implement the `isValid()` method logic
and define the message variables and message templates that correspond to the
types of validation failures that can occur. If a value fails your validation
tests, then `isValid()` should return `false`. If the value passes your
validation tests, then `isValid()` should return `true`.
In general, the `isValid()` method should not throw any exceptions, except where
it is impossible to determine whether or not the input value is valid. A few
examples of reasonable cases for throwing an exception might be if a file cannot
be opened, an LDAP server could not be contacted, or a database connection is
unavailable, where such a thing may be required for validation success or
failure to be determined.
## Creating a Validation Class
The following example demonstrates how a custom validator might be written. In
this case, the validator tests that a value is a floating point value.
```php
namespace MyValid;
use Zend\Validator\AbstractValidator;
class Float extends AbstractValidator
{
const FLOAT = 'float';
protected $messageTemplates = [
self::FLOAT => "'%value%' is not a floating point value",
];
public function isValid($value)
{
$this->setValue($value);
if (! is_float($value)) {
$this->error(self::FLOAT);
return false;
}
return true;
}
}
```
The class defines a template for its single validation failure message, which
includes the built-in magic parameter, `%value%`. The call to `setValue()`
prepares the object to insert the tested value into the failure message
automatically, should the value fail validation. The call to `error()` tracks a
reason for validation failure. Since this class only defines one failure
message, it is not necessary to provide `error()` with the name of the failure
message template.
## Writing a Validation Class having Dependent Conditions
The following example demonstrates a more complex set of validation rules:
- The input must be numeric.
- The input must fall within a range of bouncary values.
An input value would fail validation for exactly one of the following reasons:
- The input value is not numeric.
- The input value is less than the minimum allowed value.
- The input value is more than the maximum allowed value.
These validation failure reasons are then translated to definitions in the
class:
```php
namespace MyValid;
use Zend\Validator\AbstractValidator;
class NumericBetween extends AbstractValidator
{
const MSG_NUMERIC = 'msgNumeric';
const MSG_MINIMUM = 'msgMinimum';
const MSG_MAXIMUM = 'msgMaximum';
public $minimum = 0;
public $maximum = 100;
protected $messageVariables = [
'min' => 'minimum',
'max' => 'maximum',
];
protected $messageTemplates = [
self::MSG_NUMERIC => "'%value%' is not numeric",
self::MSG_MINIMUM => "'%value%' must be at least '%min%'",
self::MSG_MAXIMUM => "'%value%' must be no more than '%max%'",
];
public function isValid($value)
{
$this->setValue($value);
if (! is_numeric($value)) {
$this->error(self::MSG_NUMERIC);
return false;
}
if ($value < $this->minimum) {
$this->error(self::MSG_MINIMUM);
return false;
}
if ($value > $this->maximum) {
$this->error(self::MSG_MAXIMUM);
return false;
}
return true;
}
}
```
The public properties `$minimum` and `$maximum` have been established to provide
the minimum and maximum boundaries, respectively, for a value to successfully
validate. The class also defines two message variables that correspond to the
public properties and allow `min` and `max` to be used in message templates as
magic parameters, just as with `value`.
Note that if any one of the validation checks in `isValid()` fails, an
appropriate failure message is prepared, and the method immediately returns
`false`. These validation rules are therefore sequentially dependent; that is,
if one test should fail, there is no need to test any subsequent validation
rules. This need not be the case, however. The following example illustrates how
to write a class having independent validation rules, where the validation
object may return multiple reasons why a particular validation attempt failed.
## Validation with Independent Conditions, Multiple Reasons for Failure
Consider writing a validation class for password strength enforcement - when a
user is required to choose a password that meets certain criteria for helping
secure user accounts. Let us assume that the password security criteria enforce
that the password:
- is at least 8 characters in length,
- contains at least one uppercase letter,
- contains at least one lowercase letter,
- and contains at least one digit character.
The following class implements these validation criteria:
```php
namespace MyValid;
use Zend\Validator\AbstractValidator;
class PasswordStrength extends AbstractValidator
{
const LENGTH = 'length';
const UPPER = 'upper';
const LOWER = 'lower';
const DIGIT = 'digit';
protected $messageTemplates = [
self::LENGTH => "'%value%' must be at least 8 characters in length",
self::UPPER => "'%value%' must contain at least one uppercase letter",
self::LOWER => "'%value%' must contain at least one lowercase letter",
self::DIGIT => "'%value%' must contain at least one digit character",
];
public function isValid($value)
{
$this->setValue($value);
$isValid = true;
if (strlen($value) < 8) {
$this->error(self::LENGTH);
$isValid = false;
}
if (! preg_match('/[A-Z]/', $value)) {
$this->error(self::UPPER);
$isValid = false;
}
if (! preg_match('/[a-z]/', $value)) {
$this->error(self::LOWER);
$isValid = false;
}
if (! preg_match('/\d/', $value)) {
$this->error(self::DIGIT);
$isValid = false;
}
return $isValid;
}
}
```
Note that the four criteria tests in `isValid()` do not immediately return
`false`. This allows the validation class to provide **all** of the reasons that
the input password failed to meet the validation requirements. If, for example,
a user were to input the string `#$%` as a password, `isValid()` would cause
all four validation failure messages to be returned by a subsequent call to
`getMessages()`.

View File

@@ -0,0 +1,63 @@
docs_dir: doc/book
site_dir: doc/html
pages:
- index.md
- Intro: intro.md
- Reference:
- "Validator Chains": validator-chains.md
- "Writing Validators": writing-validators.md
- "Validation Messages": messages.md
- "Standard Validation Classes": set.md
- Validators:
- Barcode: validators/barcode.md
- Between: validators/between.md
- Callback: validators/callback.md
- CreditCard: validators/credit-card.md
- Date: validators/date.md
- "Db\\RecordExists and Db\\NoRecordExists": validators/db.md
- Digits: validators/digits.md
- EmailAddress: validators/email-address.md
- GreaterThan: validators/greater-than.md
- Hex: validators/hex.md
- Hostname: validators/hostname.md
- Iban: validators/iban.md
- Identical: validators/identical.md
- InArray: validators/in-array.md
- Ip: validators/ip.md
- Isbn: validators/isbn.md
- IsInstanceOf: validators/isinstanceof.md
- LessThan: validators/less-than.md
- NotEmpty: validators/not-empty.md
- PostCode: validators/post-code.md
- Regex: validators/regex.md
- Sitemap: validators/sitemap.md
- Step: validators/step.md
- StringLength: validators/string-length.md
- Timezone: validators/timezone.md
- Uri: validators/uri.md
- Uuid: validators/uuid.md
- "File Validators":
- Intro: validators/file/intro.md
- Count: validators/file/count.md
- Crc32: validators/file/crc32.md
- ExcludeExtension: validators/file/exclude-extension.md
- ExcludeMimeType: validators/file/exclude-mime-type.md
- Exists: validators/file/exists.md
- Extension: validators/file/extension.md
- FilesSize: validators/file/files-size.md
- Hash: validators/file/hash.md
- ImageSize: validators/file/image-size.md
- IsCompressed: validators/file/is-compressed.md
- IsImage: validators/file/is-image.md
- Md5: validators/file/md5.md
- MimeType: validators/file/mime-type.md
- NotExists: validators/file/not-exists.md
- Sha1: validators/file/sha1.md
- Size: validators/file/size.md
- Upload: validators/file/upload.md
- UploadFile: validators/file/upload-file.md
- WordCount: validators/file/word-count.md
site_name: zend-validator
site_description: zend-validator
repo_url: 'https://github.com/zendframework/zend-validator'
copyright: 'Copyright (c) 2016 <a href="http://www.zend.com/">Zend Technologies USA Inc.</a>'

View File

@@ -0,0 +1,574 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator;
use Traversable;
use Zend\Stdlib\ArrayUtils;
abstract class AbstractValidator implements
Translator\TranslatorAwareInterface,
ValidatorInterface
{
/**
* The value to be validated
*
* @var mixed
*/
protected $value;
/**
* Default translation object for all validate objects
* @var Translator\TranslatorInterface
*/
protected static $defaultTranslator;
/**
* Default text domain to be used with translator
* @var string
*/
protected static $defaultTranslatorTextDomain = 'default';
/**
* Limits the maximum returned length of an error message
*
* @var int
*/
protected static $messageLength = -1;
protected $abstractOptions = [
'messages' => [], // Array of validation failure messages
'messageTemplates' => [], // Array of validation failure message templates
'messageVariables' => [], // Array of additional variables available for validation failure messages
'translator' => null, // Translation object to used -> Translator\TranslatorInterface
'translatorTextDomain' => null, // Translation text domain
'translatorEnabled' => true, // Is translation enabled?
'valueObscured' => false, // Flag indicating whether or not value should be obfuscated
// in error messages
];
/**
* Abstract constructor for all validators
* A validator should accept following parameters:
* - nothing f.e. Validator()
* - one or multiple scalar values f.e. Validator($first, $second, $third)
* - an array f.e. Validator(array($first => 'first', $second => 'second', $third => 'third'))
* - an instance of Traversable f.e. Validator($config_instance)
*
* @param array|Traversable $options
*/
public function __construct($options = null)
{
// The abstract constructor allows no scalar values
if ($options instanceof Traversable) {
$options = ArrayUtils::iteratorToArray($options);
}
if (isset($this->messageTemplates)) {
$this->abstractOptions['messageTemplates'] = $this->messageTemplates;
}
if (isset($this->messageVariables)) {
$this->abstractOptions['messageVariables'] = $this->messageVariables;
}
if (is_array($options)) {
$this->setOptions($options);
}
}
/**
* Returns an option
*
* @param string $option Option to be returned
* @return mixed Returned option
* @throws Exception\InvalidArgumentException
*/
public function getOption($option)
{
if (array_key_exists($option, $this->abstractOptions)) {
return $this->abstractOptions[$option];
}
if (isset($this->options) && array_key_exists($option, $this->options)) {
return $this->options[$option];
}
throw new Exception\InvalidArgumentException("Invalid option '$option'");
}
/**
* Returns all available options
*
* @return array Array with all available options
*/
public function getOptions()
{
$result = $this->abstractOptions;
if (isset($this->options)) {
$result += $this->options;
}
return $result;
}
/**
* Sets one or multiple options
*
* @param array|Traversable $options Options to set
* @throws Exception\InvalidArgumentException If $options is not an array or Traversable
* @return AbstractValidator Provides fluid interface
*/
public function setOptions($options = [])
{
if (!is_array($options) && !$options instanceof Traversable) {
throw new Exception\InvalidArgumentException(__METHOD__ . ' expects an array or Traversable');
}
foreach ($options as $name => $option) {
$fname = 'set' . ucfirst($name);
$fname2 = 'is' . ucfirst($name);
if (($name != 'setOptions') && method_exists($this, $name)) {
$this->{$name}($option);
} elseif (($fname != 'setOptions') && method_exists($this, $fname)) {
$this->{$fname}($option);
} elseif (method_exists($this, $fname2)) {
$this->{$fname2}($option);
} elseif (isset($this->options)) {
$this->options[$name] = $option;
} else {
$this->abstractOptions[$name] = $option;
}
}
return $this;
}
/**
* Returns array of validation failure messages
*
* @return array
*/
public function getMessages()
{
return array_unique($this->abstractOptions['messages'], SORT_REGULAR);
}
/**
* Invoke as command
*
* @param mixed $value
* @return bool
*/
public function __invoke($value)
{
return $this->isValid($value);
}
/**
* Returns an array of the names of variables that are used in constructing validation failure messages
*
* @return array
*/
public function getMessageVariables()
{
return array_keys($this->abstractOptions['messageVariables']);
}
/**
* Returns the message templates from the validator
*
* @return array
*/
public function getMessageTemplates()
{
return $this->abstractOptions['messageTemplates'];
}
/**
* Sets the validation failure message template for a particular key
*
* @param string $messageString
* @param string $messageKey OPTIONAL
* @return AbstractValidator Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function setMessage($messageString, $messageKey = null)
{
if ($messageKey === null) {
$keys = array_keys($this->abstractOptions['messageTemplates']);
foreach ($keys as $key) {
$this->setMessage($messageString, $key);
}
return $this;
}
if (!isset($this->abstractOptions['messageTemplates'][$messageKey])) {
throw new Exception\InvalidArgumentException("No message template exists for key '$messageKey'");
}
$this->abstractOptions['messageTemplates'][$messageKey] = $messageString;
return $this;
}
/**
* Sets validation failure message templates given as an array, where the array keys are the message keys,
* and the array values are the message template strings.
*
* @param array $messages
* @return AbstractValidator
*/
public function setMessages(array $messages)
{
foreach ($messages as $key => $message) {
$this->setMessage($message, $key);
}
return $this;
}
/**
* Magic function returns the value of the requested property, if and only if it is the value or a
* message variable.
*
* @param string $property
* @return mixed
* @throws Exception\InvalidArgumentException
*/
public function __get($property)
{
if ($property == 'value') {
return $this->value;
}
if (array_key_exists($property, $this->abstractOptions['messageVariables'])) {
$result = $this->abstractOptions['messageVariables'][$property];
if (is_array($result)) {
return $this->{key($result)}[current($result)];
}
return $this->{$result};
}
if (isset($this->messageVariables) && array_key_exists($property, $this->messageVariables)) {
$result = $this->{$this->messageVariables[$property]};
if (is_array($result)) {
return $this->{key($result)}[current($result)];
}
return $this->{$result};
}
throw new Exception\InvalidArgumentException("No property exists by the name '$property'");
}
/**
* Constructs and returns a validation failure message with the given message key and value.
*
* Returns null if and only if $messageKey does not correspond to an existing template.
*
* If a translator is available and a translation exists for $messageKey,
* the translation will be used.
*
* @param string $messageKey
* @param string|array|object $value
* @return string
*/
protected function createMessage($messageKey, $value)
{
if (!isset($this->abstractOptions['messageTemplates'][$messageKey])) {
return;
}
$message = $this->abstractOptions['messageTemplates'][$messageKey];
$message = $this->translateMessage($messageKey, $message);
if (is_object($value) &&
!in_array('__toString', get_class_methods($value))
) {
$value = get_class($value) . ' object';
} elseif (is_array($value)) {
$value = var_export($value, 1);
} else {
$value = (string) $value;
}
if ($this->isValueObscured()) {
$value = str_repeat('*', strlen($value));
}
$message = str_replace('%value%', (string) $value, $message);
foreach ($this->abstractOptions['messageVariables'] as $ident => $property) {
if (is_array($property)) {
$value = $this->{key($property)}[current($property)];
if (is_array($value)) {
$value = '[' . implode(', ', $value) . ']';
}
} else {
$value = $this->$property;
}
$message = str_replace("%$ident%", (string) $value, $message);
}
$length = self::getMessageLength();
if (($length > -1) && (strlen($message) > $length)) {
$message = substr($message, 0, ($length - 3)) . '...';
}
return $message;
}
/**
* @param string $messageKey
* @param string $value OPTIONAL
* @return void
*/
protected function error($messageKey, $value = null)
{
if ($messageKey === null) {
$keys = array_keys($this->abstractOptions['messageTemplates']);
$messageKey = current($keys);
}
if ($value === null) {
$value = $this->value;
}
$this->abstractOptions['messages'][$messageKey] = $this->createMessage($messageKey, $value);
}
/**
* Returns the validation value
*
* @return mixed Value to be validated
*/
protected function getValue()
{
return $this->value;
}
/**
* Sets the value to be validated and clears the messages and errors arrays
*
* @param mixed $value
* @return void
*/
protected function setValue($value)
{
$this->value = $value;
$this->abstractOptions['messages'] = [];
}
/**
* Set flag indicating whether or not value should be obfuscated in messages
*
* @param bool $flag
* @return AbstractValidator
*/
public function setValueObscured($flag)
{
$this->abstractOptions['valueObscured'] = (bool) $flag;
return $this;
}
/**
* Retrieve flag indicating whether or not value should be obfuscated in
* messages
*
* @return bool
*/
public function isValueObscured()
{
return $this->abstractOptions['valueObscured'];
}
/**
* Set translation object
*
* @param Translator\TranslatorInterface|null $translator
* @param string $textDomain (optional)
* @return AbstractValidator
* @throws Exception\InvalidArgumentException
*/
public function setTranslator(Translator\TranslatorInterface $translator = null, $textDomain = null)
{
$this->abstractOptions['translator'] = $translator;
if (null !== $textDomain) {
$this->setTranslatorTextDomain($textDomain);
}
return $this;
}
/**
* Return translation object
*
* @return Translator\TranslatorInterface|null
*/
public function getTranslator()
{
if (! $this->isTranslatorEnabled()) {
return;
}
if (null === $this->abstractOptions['translator']) {
$this->abstractOptions['translator'] = self::getDefaultTranslator();
}
return $this->abstractOptions['translator'];
}
/**
* Does this validator have its own specific translator?
*
* @return bool
*/
public function hasTranslator()
{
return (bool) $this->abstractOptions['translator'];
}
/**
* Set translation text domain
*
* @param string $textDomain
* @return AbstractValidator
*/
public function setTranslatorTextDomain($textDomain = 'default')
{
$this->abstractOptions['translatorTextDomain'] = $textDomain;
return $this;
}
/**
* Return the translation text domain
*
* @return string
*/
public function getTranslatorTextDomain()
{
if (null === $this->abstractOptions['translatorTextDomain']) {
$this->abstractOptions['translatorTextDomain'] =
self::getDefaultTranslatorTextDomain();
}
return $this->abstractOptions['translatorTextDomain'];
}
/**
* Set default translation object for all validate objects
*
* @param Translator\TranslatorInterface|null $translator
* @param string $textDomain (optional)
* @return void
* @throws Exception\InvalidArgumentException
*/
public static function setDefaultTranslator(Translator\TranslatorInterface $translator = null, $textDomain = null)
{
static::$defaultTranslator = $translator;
if (null !== $textDomain) {
self::setDefaultTranslatorTextDomain($textDomain);
}
}
/**
* Get default translation object for all validate objects
*
* @return Translator\TranslatorInterface|null
*/
public static function getDefaultTranslator()
{
return static::$defaultTranslator;
}
/**
* Is there a default translation object set?
*
* @return bool
*/
public static function hasDefaultTranslator()
{
return (bool) static::$defaultTranslator;
}
/**
* Set default translation text domain for all validate objects
*
* @param string $textDomain
* @return void
*/
public static function setDefaultTranslatorTextDomain($textDomain = 'default')
{
static::$defaultTranslatorTextDomain = $textDomain;
}
/**
* Get default translation text domain for all validate objects
*
* @return string
*/
public static function getDefaultTranslatorTextDomain()
{
return static::$defaultTranslatorTextDomain;
}
/**
* Indicate whether or not translation should be enabled
*
* @param bool $flag
* @return AbstractValidator
*/
public function setTranslatorEnabled($flag = true)
{
$this->abstractOptions['translatorEnabled'] = (bool) $flag;
return $this;
}
/**
* Is translation enabled?
*
* @return bool
*/
public function isTranslatorEnabled()
{
return $this->abstractOptions['translatorEnabled'];
}
/**
* Returns the maximum allowed message length
*
* @return int
*/
public static function getMessageLength()
{
return static::$messageLength;
}
/**
* Sets the maximum allowed message length
*
* @param int $length
*/
public static function setMessageLength($length = -1)
{
static::$messageLength = $length;
}
/**
* Translate a validation message
*
* @param string $messageKey
* @param string $message
* @return string
*/
protected function translateMessage($messageKey, $message)
{
$translator = $this->getTranslator();
if (!$translator) {
return $message;
}
return $translator->translate($message, $this->getTranslatorTextDomain());
}
}

View File

@@ -0,0 +1,187 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator;
use Traversable;
class Barcode extends AbstractValidator
{
const INVALID = 'barcodeInvalid';
const FAILED = 'barcodeFailed';
const INVALID_CHARS = 'barcodeInvalidChars';
const INVALID_LENGTH = 'barcodeInvalidLength';
protected $messageTemplates = [
self::FAILED => "The input failed checksum validation",
self::INVALID_CHARS => "The input contains invalid characters",
self::INVALID_LENGTH => "The input should have a length of %length% characters",
self::INVALID => "Invalid type given. String expected",
];
/**
* Additional variables available for validation failure messages
*
* @var array
*/
protected $messageVariables = [
'length' => ['options' => 'length'],
];
protected $options = [
'adapter' => null, // Barcode adapter Zend\Validator\Barcode\AbstractAdapter
'options' => null, // Options for this adapter
'length' => null,
'useChecksum' => null,
];
/**
* Constructor for barcodes
*
* @param array|string $options Options to use
*/
public function __construct($options = null)
{
if ($options === null) {
$options = [];
}
if (!is_array($options) && !($options instanceof Traversable)) {
$options = ['adapter' => $options];
}
if (array_key_exists('options', $options)) {
$options['options'] = ['options' => $options['options']];
}
parent::__construct($options);
}
/**
* Returns the set adapter
*
* @return Barcode\AbstractAdapter
*/
public function getAdapter()
{
if (!($this->options['adapter'] instanceof Barcode\AdapterInterface)) {
$this->setAdapter('Ean13');
}
return $this->options['adapter'];
}
/**
* Sets a new barcode adapter
*
* @param string|Barcode\AbstractAdapter $adapter Barcode adapter to use
* @param array $options Options for this adapter
* @return Barcode
* @throws Exception\InvalidArgumentException
*/
public function setAdapter($adapter, $options = null)
{
if (is_string($adapter)) {
$adapter = ucfirst(strtolower($adapter));
$adapter = 'Zend\\Validator\\Barcode\\' . $adapter;
if (!class_exists($adapter)) {
throw new Exception\InvalidArgumentException('Barcode adapter matching "' . $adapter . '" not found');
}
$adapter = new $adapter($options);
}
if (!$adapter instanceof Barcode\AdapterInterface) {
throw new Exception\InvalidArgumentException(
sprintf(
"Adapter %s does not implement Zend\\Validator\\Barcode\\AdapterInterface",
(is_object($adapter) ? get_class($adapter) : gettype($adapter))
)
);
}
$this->options['adapter'] = $adapter;
return $this;
}
/**
* Returns the checksum option
*
* @return string
*/
public function getChecksum()
{
return $this->getAdapter()->getChecksum();
}
/**
* Sets if checksum should be validated, if no value is given the actual setting is returned
*
* @param bool $checksum
* @return bool
*/
public function useChecksum($checksum = null)
{
return $this->getAdapter()->useChecksum($checksum);
}
/**
* Defined by Zend\Validator\ValidatorInterface
*
* Returns true if and only if $value contains a valid barcode
*
* @param string $value
* @return bool
*/
public function isValid($value)
{
if (!is_string($value)) {
$this->error(self::INVALID);
return false;
}
$this->setValue($value);
$adapter = $this->getAdapter();
$this->options['length'] = $adapter->getLength();
$result = $adapter->hasValidLength($value);
if (!$result) {
if (is_array($this->options['length'])) {
$temp = $this->options['length'];
$this->options['length'] = "";
foreach ($temp as $length) {
$this->options['length'] .= "/";
$this->options['length'] .= $length;
}
$this->options['length'] = substr($this->options['length'], 1);
}
$this->error(self::INVALID_LENGTH);
return false;
}
$result = $adapter->hasValidCharacters($value);
if (!$result) {
$this->error(self::INVALID_CHARS);
return false;
}
if ($this->useChecksum(null)) {
$result = $adapter->hasValidChecksum($value);
if (!$result) {
$this->error(self::FAILED);
return false;
}
}
return true;
}
}

View File

@@ -0,0 +1,310 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
abstract class AbstractAdapter implements AdapterInterface
{
/**
* Allowed options for this adapter
* @var array
*/
protected $options = [
'length' => null, // Allowed barcode lengths, integer, array, string
'characters' => null, // Allowed barcode characters
'checksum' => null, // Callback to checksum function
'useChecksum' => true, // Is a checksum value included?, boolean
];
/**
* Checks the length of a barcode
*
* @param string $value The barcode to check for proper length
* @return bool
*/
public function hasValidLength($value)
{
if (!is_string($value)) {
return false;
}
$fixum = strlen($value);
$found = false;
$length = $this->getLength();
if (is_array($length)) {
foreach ($length as $value) {
if ($fixum == $value) {
$found = true;
}
if ($value == -1) {
$found = true;
}
}
} elseif ($fixum == $length) {
$found = true;
} elseif ($length == -1) {
$found = true;
} elseif ($length == 'even') {
$count = $fixum % 2;
$found = (0 == $count);
} elseif ($length == 'odd') {
$count = $fixum % 2;
$found = (1 == $count);
}
return $found;
}
/**
* Checks for allowed characters within the barcode
*
* @param string $value The barcode to check for allowed characters
* @return bool
*/
public function hasValidCharacters($value)
{
if (!is_string($value)) {
return false;
}
$characters = $this->getCharacters();
if ($characters == 128) {
for ($x = 0; $x < 128; ++$x) {
$value = str_replace(chr($x), '', $value);
}
} else {
$chars = str_split($characters);
foreach ($chars as $char) {
$value = str_replace($char, '', $value);
}
}
if (strlen($value) > 0) {
return false;
}
return true;
}
/**
* Validates the checksum
*
* @param string $value The barcode to check the checksum for
* @return bool
*/
public function hasValidChecksum($value)
{
$checksum = $this->getChecksum();
if (!empty($checksum)) {
if (method_exists($this, $checksum)) {
return $this->$checksum($value);
}
}
return false;
}
/**
* Returns the allowed barcode length
*
* @return int|array
*/
public function getLength()
{
return $this->options['length'];
}
/**
* Returns the allowed characters
*
* @return int|string|array
*/
public function getCharacters()
{
return $this->options['characters'];
}
/**
* Returns the checksum function name
*
*/
public function getChecksum()
{
return $this->options['checksum'];
}
/**
* Sets the checksum validation method
*
* @param callable $checksum Checksum method to call
* @return AbstractAdapter
*/
protected function setChecksum($checksum)
{
$this->options['checksum'] = $checksum;
return $this;
}
/**
* Sets the checksum validation, if no value is given, the actual setting is returned
*
* @param bool $check
* @return AbstractAdapter|bool
*/
public function useChecksum($check = null)
{
if ($check === null) {
return $this->options['useChecksum'];
}
$this->options['useChecksum'] = (bool) $check;
return $this;
}
/**
* Sets the length of this barcode
*
* @param int|array $length
* @return AbstractAdapter
*/
protected function setLength($length)
{
$this->options['length'] = $length;
return $this;
}
/**
* Sets the allowed characters of this barcode
*
* @param int $characters
* @return AbstractAdapter
*/
protected function setCharacters($characters)
{
$this->options['characters'] = $characters;
return $this;
}
/**
* Validates the checksum (Modulo 10)
* GTIN implementation factor 3
*
* @param string $value The barcode to validate
* @return bool
*/
protected function gtin($value)
{
$barcode = substr($value, 0, -1);
$sum = 0;
$length = strlen($barcode) - 1;
for ($i = 0; $i <= $length; $i++) {
if (($i % 2) === 0) {
$sum += $barcode[$length - $i] * 3;
} else {
$sum += $barcode[$length - $i];
}
}
$calc = $sum % 10;
$checksum = ($calc === 0) ? 0 : (10 - $calc);
if ($value[$length + 1] != $checksum) {
return false;
}
return true;
}
/**
* Validates the checksum (Modulo 10)
* IDENTCODE implementation factors 9 and 4
*
* @param string $value The barcode to validate
* @return bool
*/
protected function identcode($value)
{
$barcode = substr($value, 0, -1);
$sum = 0;
$length = strlen($value) - 2;
for ($i = 0; $i <= $length; $i++) {
if (($i % 2) === 0) {
$sum += $barcode[$length - $i] * 4;
} else {
$sum += $barcode[$length - $i] * 9;
}
}
$calc = $sum % 10;
$checksum = ($calc === 0) ? 0 : (10 - $calc);
if ($value[$length + 1] != $checksum) {
return false;
}
return true;
}
/**
* Validates the checksum (Modulo 10)
* CODE25 implementation factor 3
*
* @param string $value The barcode to validate
* @return bool
*/
protected function code25($value)
{
$barcode = substr($value, 0, -1);
$sum = 0;
$length = strlen($barcode) - 1;
for ($i = 0; $i <= $length; $i++) {
if (($i % 2) === 0) {
$sum += $barcode[$i] * 3;
} else {
$sum += $barcode[$i];
}
}
$calc = $sum % 10;
$checksum = ($calc === 0) ? 0 : (10 - $calc);
if ($value[$length + 1] != $checksum) {
return false;
}
return true;
}
/**
* Validates the checksum ()
* POSTNET implementation
*
* @param string $value The barcode to validate
* @return bool
*/
protected function postnet($value)
{
$checksum = substr($value, -1, 1);
$values = str_split(substr($value, 0, -1));
$check = 0;
foreach ($values as $row) {
$check += $row;
}
$check %= 10;
$check = 10 - $check;
if ($check == $checksum) {
return true;
}
return false;
}
}

View File

@@ -0,0 +1,66 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
interface AdapterInterface
{
/**
* Checks the length of a barcode
*
* @param string $value The barcode to check for proper length
* @return bool
*/
public function hasValidLength($value);
/**
* Checks for allowed characters within the barcode
*
* @param string $value The barcode to check for allowed characters
* @return bool
*/
public function hasValidCharacters($value);
/**
* Validates the checksum
*
* @param string $value The barcode to check the checksum for
* @return bool
*/
public function hasValidChecksum($value);
/**
* Returns the allowed barcode length
*
* @return int|array
*/
public function getLength();
/**
* Returns the allowed characters
*
* @return int|string|array
*/
public function getCharacters();
/**
* Returns if barcode uses a checksum
*
* @return bool
*/
public function getChecksum();
/**
* Sets the checksum validation, if no value is given, the actual setting is returned
*
* @param bool $check
* @return AbstractAdapter|bool
*/
public function useChecksum($check = null);
}

View File

@@ -0,0 +1,66 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Codabar extends AbstractAdapter
{
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength(-1);
$this->setCharacters('0123456789-$:/.+ABCDTN*E');
$this->useChecksum(false);
}
/**
* Checks for allowed characters
* @see Zend\Validator\Barcode.AbstractAdapter::checkChars()
*/
public function hasValidCharacters($value)
{
if (strpbrk($value, 'ABCD')) {
$first = $value[0];
if (!strpbrk($first, 'ABCD')) {
// Missing start char
return false;
}
$last = substr($value, -1, 1);
if (!strpbrk($last, 'ABCD')) {
// Missing stop char
return false;
}
$value = substr($value, 1, -1);
} elseif (strpbrk($value, 'TN*E')) {
$first = $value[0];
if (!strpbrk($first, 'TN*E')) {
// Missing start char
return false;
}
$last = substr($value, -1, 1);
if (!strpbrk($last, 'TN*E')) {
// Missing stop char
return false;
}
$value = substr($value, 1, -1);
}
$chars = $this->getCharacters();
$this->setCharacters('0123456789-$:/.+');
$result = parent::hasValidCharacters($value);
$this->setCharacters($chars);
return $result;
}
}

View File

@@ -0,0 +1,448 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
use Zend\Stdlib\StringUtils;
use Zend\Stdlib\StringWrapper\StringWrapperInterface;
use Zend\Validator\Exception;
class Code128 extends AbstractAdapter
{
/**
* The used string wrapper used for basic UTF-8 string functions
*
* @var StringWrapperInterface
*/
protected $utf8StringWrapper;
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength(-1);
$this->setCharacters([
'A' => [
0 => ' ', 1 => '!', 2 => '"', 3 => '#', 4 => '$', 5 => '%', 6 => '&', 7 => "'",
8 => '(', 9 => ')', 10 => '*', 11 => '+', 12 => ',', 13 => '-', 14 => '.', 15 => '/',
16 => '0', 17 => '1', 18 => '2', 19 => '3', 20 => '4', 21 => '5', 22 => '6', 23 => '7',
24 => '8', 25 => '9', 26 => ':', 27 => ';', 28 => '<', 29 => '=', 30 => '>', 31 => '?',
32 => '@', 33 => 'A', 34 => 'B', 35 => 'C', 36 => 'D', 37 => 'E', 38 => 'F', 39 => 'G',
40 => 'H', 41 => 'I', 42 => 'J', 43 => 'K', 44 => 'L', 45 => 'M', 46 => 'N', 47 => 'O',
48 => 'P', 49 => 'Q', 50 => 'R', 51 => 'S', 52 => 'T', 53 => 'U', 54 => 'V', 55 => 'W',
56 => 'X', 57 => 'Y', 58 => 'Z', 59 => '[', 60 => '\\', 61 => ']', 62 => '^', 63 => '_',
64 =>0x00, 65 =>0x01, 66 =>0x02, 67 =>0x03, 68 =>0x04, 69 =>0x05, 70 =>0x06, 71 =>0x07,
72 =>0x08, 73 =>0x09, 74 =>0x0A, 75 =>0x0B, 76 =>0x0C, 77 =>0x0D, 78 =>0x0E, 79 =>0x0F,
80 =>0x10, 81 =>0x11, 82 =>0x12, 83 =>0x13, 84 =>0x14, 85 =>0x15, 86 =>0x16, 87 =>0x17,
88 =>0x18, 89 =>0x19, 90 =>0x1A, 91 =>0x1B, 92 =>0x1C, 93 =>0x1D, 94 =>0x1E, 95 =>0x1F,
96 => 'Ç', 97 => 'ü', 98 => 'é', 99 => 'â', 100 => 'ä', 101 => 'à', 102 => 'å', 103 => '‡',
104 => 'ˆ', 105 => '‰', 106 => 'Š'],
'B' => [
0 => ' ', 1 => '!', 2 => '"', 3 => '#', 4 => '$', 5 => '%', 6 => '&', 7 => "'",
8 => '(', 9 => ')', 10 => '*', 11 => '+', 12 => ',', 13 => '-', 14 => '.', 15 => '/',
16 => '0', 17 => '1', 18 => '2', 19 => '3', 20 => '4', 21 => '5', 22 => '6', 23 => '7',
24 => '8', 25 => '9', 26 => ':', 27 => ';', 28 => '<', 29 => '=', 30 => '>', 31 => '?',
32 => '@', 33 => 'A', 34 => 'B', 35 => 'C', 36 => 'D', 37 => 'E', 38 => 'F', 39 => 'G',
40 => 'H', 41 => 'I', 42 => 'J', 43 => 'K', 44 => 'L', 45 => 'M', 46 => 'N', 47 => 'O',
48 => 'P', 49 => 'Q', 50 => 'R', 51 => 'S', 52 => 'T', 53 => 'U', 54 => 'V', 55 => 'W',
56 => 'X', 57 => 'Y', 58 => 'Z', 59 => '[', 60 => '\\', 61 => ']', 62 => '^', 63 => '_',
64 => '`', 65 => 'a', 66 => 'b', 67 => 'c', 68 => 'd', 69 => 'e', 70 => 'f', 71 => 'g',
72 => 'h', 73 => 'i', 74 => 'j', 75 => 'k', 76 => 'l', 77 => 'm', 78 => 'n', 79 => 'o',
80 => 'p', 81 => 'q', 82 => 'r', 83 => 's', 84 => 't', 85 => 'u', 86 => 'v', 87 => 'w',
88 => 'x', 89 => 'y', 90 => 'z', 91 => '{', 92 => '|', 93 => '}', 94 => '~', 95 =>0x7F,
96 => 'Ç', 97 => 'ü', 98 => 'é', 99 => 'â', 100 => 'ä', 101 => 'à', 102 => 'å', 103 => '‡',
104 => 'ˆ', 105 => '‰', 106 => 'Š'],
'C' => [
0 => '00', 1 => '01', 2 => '02', 3 => '03', 4 => '04', 5 => '05', 6 => '06', 7 => '07',
8 => '08', 9 => '09', 10 => '10', 11 => '11', 12 => '12', 13 => '13', 14 => '14', 15 => '15',
16 => '16', 17 => '17', 18 => '18', 19 => '19', 20 => '20', 21 => '21', 22 => '22', 23 => '23',
24 => '24', 25 => '25', 26 => '26', 27 => '27', 28 => '28', 29 => '29', 30 => '30', 31 => '31',
32 => '32', 33 => '33', 34 => '34', 35 => '35', 36 => '36', 37 => '37', 38 => '38', 39 => '39',
40 => '40', 41 => '41', 42 => '42', 43 => '43', 44 => '44', 45 => '45', 46 => '46', 47 => '47',
48 => '48', 49 => '49', 50 => '50', 51 => '51', 52 => '52', 53 => '53', 54 => '54', 55 => '55',
56 => '56', 57 => '57', 58 => '58', 59 => '59', 60 => '60', 61 => '61', 62 => '62', 63 => '63',
64 => '64', 65 => '65', 66 => '66', 67 => '67', 68 => '68', 69 => '69', 70 => '70', 71 => '71',
72 => '72', 73 => '73', 74 => '74', 75 => '75', 76 => '76', 77 => '77', 78 => '78', 79 => '79',
80 => '80', 81 => '81', 82 => '82', 83 => '83', 84 => '84', 85 => '85', 86 => '86', 87 => '87',
88 => '88', 89 => '89', 90 => '90', 91 => '91', 92 => '92', 93 => '93', 94 => '94', 95 => '95',
96 => '96', 97 => '97', 98 => '98', 99 => '99', 100 => 'ä', 101 => 'à', 102 => 'å', 103 => '‡',
104 => 'ˆ', 105 => '‰', 106 => 'Š']
]);
$this->setChecksum('code128');
}
public function setUtf8StringWrapper(StringWrapperInterface $utf8StringWrapper)
{
if (!$utf8StringWrapper->isSupported('UTF-8')) {
throw new Exception\InvalidArgumentException(
"The string wrapper needs to support UTF-8 character encoding"
);
}
$this->utf8StringWrapper = $utf8StringWrapper;
}
/**
* Get the string wrapper supporting UTF-8 character encoding
*
* @return StringWrapperInterface
*/
public function getUtf8StringWrapper()
{
if (!$this->utf8StringWrapper) {
$this->utf8StringWrapper = StringUtils::getWrapper('UTF-8');
}
return $this->utf8StringWrapper;
}
/**
* Checks for allowed characters within the barcode
*
* @param string $value The barcode to check for allowed characters
* @return bool
*/
public function hasValidCharacters($value)
{
if (!is_string($value)) {
return false;
}
// get used string wrapper for UTF-8 character encoding
$strWrapper = $this->getUtf8StringWrapper();
// detect starting charset
$set = $this->getCodingSet($value);
$read = $set;
if ($set != '') {
$value = $strWrapper->substr($value, 1, null);
}
// process barcode
while ($value != '') {
$char = $strWrapper->substr($value, 0, 1);
switch ($char) {
// Function definition
case 'Ç':
case 'ü':
case 'å':
break;
// Switch 1 char between A and B
case 'é':
if ($set == 'A') {
$read = 'B';
} elseif ($set == 'B') {
$read = 'A';
}
break;
// Switch to C
case 'â':
$set = 'C';
$read = 'C';
break;
// Switch to B
case 'ä':
$set = 'B';
$read = 'B';
break;
// Switch to A
case 'à':
$set = 'A';
$read = 'A';
break;
// Doubled start character
case '‡':
case 'ˆ':
case '‰':
return false;
// Chars after the stop character
case 'Š':
break 2;
default:
// Does the char exist within the charset to read?
if ($this->ord128($char, $read) == -1) {
return false;
}
break;
}
$value = $strWrapper->substr($value, 1, null);
$read = $set;
}
if (($value != '') && ($strWrapper->strlen($value) != 1)) {
return false;
}
return true;
}
/**
* Validates the checksum ()
*
* @param string $value The barcode to validate
* @return bool
*/
protected function code128($value)
{
$sum = 0;
$pos = 1;
$set = $this->getCodingSet($value);
$read = $set;
$usecheck = $this->useChecksum(null);
$strWrapper = $this->getUtf8StringWrapper();
$char = $strWrapper->substr($value, 0, 1);
if ($char == '‡') {
$sum = 103;
} elseif ($char == 'ˆ') {
$sum = 104;
} elseif ($char == '‰') {
$sum = 105;
} elseif ($usecheck == true) {
// no start value, unable to detect a proper checksum
return false;
}
$value = $strWrapper->substr($value, 1, null);
while ($strWrapper->strpos($value, 'Š') || ($value != '')) {
$char = $strWrapper->substr($value, 0, 1);
if ($read == 'C') {
$char = $strWrapper->substr($value, 0, 2);
}
switch ($char) {
// Function definition
case 'Ç':
case 'ü':
case 'å':
$sum += ($pos * $this->ord128($char, $set));
break;
case 'é':
$sum += ($pos * $this->ord128($char, $set));
if ($set == 'A') {
$read = 'B';
} elseif ($set == 'B') {
$read = 'A';
}
break;
// Switch to C
case 'â':
$sum += ($pos * $this->ord128($char, $set));
$set = 'C';
$read = 'C';
break;
// Switch to B
case 'ä':
$sum += ($pos * $this->ord128($char, $set));
$set = 'B';
$read = 'B';
break;
// Switch to A
case 'à':
$sum += ($pos * $this->ord128($char, $set));
$set = 'A';
$read = 'A';
break;
case '‡':
case 'ˆ':
case '‰':
return false;
break;
default:
// Does the char exist within the charset to read?
if ($this->ord128($char, $read) == -1) {
return false;
}
$sum += ($pos * $this->ord128($char, $set));
break;
}
$value = $strWrapper->substr($value, 1);
++$pos;
if (($strWrapper->strpos($value, 'Š') == 1) && ($strWrapper->strlen($value) == 2)) {
// break by stop and checksum char
break;
}
$read = $set;
}
if (($strWrapper->strpos($value, 'Š') != 1) || ($strWrapper->strlen($value) != 2)) {
// return false if checksum is not readable and true if no startvalue is detected
return (!$usecheck);
}
$mod = $sum % 103;
if ($strWrapper->substr($value, 0, 1) == $this->chr128($mod, $set)) {
return true;
}
return false;
}
/**
* Returns the coding set for a barcode
*
* @param string $value Barcode
* @return string
*/
protected function getCodingSet($value)
{
$value = $this->getUtf8StringWrapper()->substr($value, 0, 1);
switch ($value) {
case '‡':
return 'A';
break;
case 'ˆ':
return 'B';
break;
case '‰':
return 'C';
break;
}
return '';
}
/**
* Internal method to return the code128 integer from an ascii value
*
* Table A
* ASCII CODE128
* 32 to 95 == 0 to 63
* 0 to 31 == 64 to 95
* 128 to 138 == 96 to 106
*
* Table B
* ASCII CODE128
* 32 to 138 == 0 to 106
*
* Table C
* ASCII CODE128
* "00" to "99" == 0 to 99
* 132 to 138 == 100 to 106
*
* @param string $value
* @param string $set
* @return int
*/
protected function ord128($value, $set)
{
$ord = ord($value);
if ($set == 'A') {
if ($ord < 32) {
return ($ord + 64);
} elseif ($ord < 96) {
return ($ord - 32);
} elseif ($ord > 138) {
return -1;
} else {
return ($ord - 32);
}
} elseif ($set == 'B') {
if ($ord < 32) {
return -1;
} elseif ($ord <= 138) {
return ($ord - 32);
} else {
return -1;
}
} elseif ($set == 'C') {
$val = (int) $value;
if (($val >= 0) && ($val <= 99)) {
return $val;
} elseif (($ord >= 132) && ($ord <= 138)) {
return ($ord - 32);
} else {
return -1;
}
} else {
if ($ord < 32) {
return ($ord +64);
} elseif ($ord <= 138) {
return ($ord - 32);
} else {
return -1;
}
}
}
/**
* Internal Method to return the ascii value from a code128 integer
*
* Table A
* ASCII CODE128
* 32 to 95 == 0 to 63
* 0 to 31 == 64 to 95
* 128 to 138 == 96 to 106
*
* Table B
* ASCII CODE128
* 32 to 138 == 0 to 106
*
* Table C
* ASCII CODE128
* "00" to "99" == 0 to 99
* 132 to 138 == 100 to 106
*
* @param int $value
* @param string $set
* @return string
*/
protected function chr128($value, $set)
{
if ($set == 'A') {
if ($value < 64) {
return chr($value + 32);
} elseif ($value < 96) {
return chr($value - 64);
} elseif ($value > 106) {
return -1;
} else {
return chr($value + 32);
}
} elseif ($set == 'B') {
if ($value > 106) {
return -1;
} else {
return chr($value + 32);
}
} elseif ($set == 'C') {
if (($value >= 0) && ($value <= 9)) {
return "0" . (string) $value;
} elseif ($value <= 99) {
return (string) $value;
} elseif ($value <= 106) {
return chr($value + 32);
} else {
return -1;
}
} else {
if ($value <= 106) {
return ($value + 32);
} else {
return -1;
}
}
}
}

View File

@@ -0,0 +1,24 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Code25 extends AbstractAdapter
{
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength(-1);
$this->setCharacters('0123456789');
$this->setChecksum('code25');
$this->useChecksum(false);
}
}

View File

@@ -0,0 +1,26 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Code25interleaved extends AbstractAdapter
{
/**
* Constructor
*
* Sets check flag to false.
*/
public function __construct()
{
$this->setLength('even');
$this->setCharacters('0123456789');
$this->setChecksum('code25');
$this->useChecksum(false);
}
}

View File

@@ -0,0 +1,60 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Code39 extends AbstractAdapter
{
/**
* @var array
*/
protected $check = [
'0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6,
'7' => 7, '8' => 8, '9' => 9, 'A' => 10, 'B' => 11, 'C' => 12, 'D' => 13,
'E' => 14, 'F' => 15, 'G' => 16, 'H' => 17, 'I' => 18, 'J' => 19, 'K' => 20,
'L' => 21, 'M' => 22, 'N' => 23, 'O' => 24, 'P' => 25, 'Q' => 26, 'R' => 27,
'S' => 28, 'T' => 29, 'U' => 30, 'V' => 31, 'W' => 32, 'X' => 33, 'Y' => 34,
'Z' => 35, '-' => 36, '.' => 37, ' ' => 38, '$' => 39, '/' => 40, '+' => 41,
'%' => 42,
];
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength(-1);
$this->setCharacters('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ -.$/+%');
$this->setChecksum('code39');
$this->useChecksum(false);
}
/**
* Validates the checksum (Modulo 43)
*
* @param string $value The barcode to validate
* @return bool
*/
protected function code39($value)
{
$checksum = substr($value, -1, 1);
$value = str_split(substr($value, 0, -1));
$count = 0;
foreach ($value as $char) {
$count += $this->check[$char];
}
$mod = $count % 43;
if ($mod == $this->check[$checksum]) {
return true;
}
return false;
}
}

View File

@@ -0,0 +1,23 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Code39ext extends AbstractAdapter
{
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength(-1);
$this->setCharacters(128);
$this->useChecksum(false);
}
}

View File

@@ -0,0 +1,80 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Code93 extends AbstractAdapter
{
/**
* Note that the characters !"§& are only synonyms
* @var array
*/
protected $check = [
'0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4, '5' => 5, '6' => 6,
'7' => 7, '8' => 8, '9' => 9, 'A' => 10, 'B' => 11, 'C' => 12, 'D' => 13,
'E' => 14, 'F' => 15, 'G' => 16, 'H' => 17, 'I' => 18, 'J' => 19, 'K' => 20,
'L' => 21, 'M' => 22, 'N' => 23, 'O' => 24, 'P' => 25, 'Q' => 26, 'R' => 27,
'S' => 28, 'T' => 29, 'U' => 30, 'V' => 31, 'W' => 32, 'X' => 33, 'Y' => 34,
'Z' => 35, '-' => 36, '.' => 37, ' ' => 38, '$' => 39, '/' => 40, '+' => 41,
'%' => 42, '!' => 43, '"' => 44, '§' => 45, '&' => 46,
];
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength(-1);
$this->setCharacters('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ -.$/+%');
$this->setChecksum('code93');
$this->useChecksum(false);
}
/**
* Validates the checksum (Modulo CK)
*
* @param string $value The barcode to validate
* @return bool
*/
protected function code93($value)
{
$checksum = substr($value, -2, 2);
$value = str_split(substr($value, 0, -2));
$count = 0;
$length = count($value) % 20;
foreach ($value as $char) {
if ($length == 0) {
$length = 20;
}
$count += $this->check[$char] * $length;
--$length;
}
$check = array_search(($count % 47), $this->check);
$value[] = $check;
$count = 0;
$length = count($value) % 15;
foreach ($value as $char) {
if ($length == 0) {
$length = 15;
}
$count += $this->check[$char] * $length;
--$length;
}
$check .= array_search(($count % 47), $this->check);
if ($check == $checksum) {
return true;
}
return false;
}
}

View File

@@ -0,0 +1,23 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Code93ext extends AbstractAdapter
{
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength(-1);
$this->setCharacters(128);
$this->useChecksum(false);
}
}

View File

@@ -0,0 +1,23 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Ean12 extends AbstractAdapter
{
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength(12);
$this->setCharacters('0123456789');
$this->setChecksum('gtin');
}
}

View File

@@ -0,0 +1,23 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Ean13 extends AbstractAdapter
{
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength(13);
$this->setCharacters('0123456789');
$this->setChecksum('gtin');
}
}

View File

@@ -0,0 +1,23 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Ean14 extends AbstractAdapter
{
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength(14);
$this->setCharacters('0123456789');
$this->setChecksum('gtin');
}
}

View File

@@ -0,0 +1,23 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Ean18 extends AbstractAdapter
{
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength(18);
$this->setCharacters('0123456789');
$this->setChecksum('gtin');
}
}

View File

@@ -0,0 +1,23 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Ean2 extends AbstractAdapter
{
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength(2);
$this->setCharacters('0123456789');
$this->useChecksum(false);
}
}

View File

@@ -0,0 +1,25 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Ean5 extends AbstractAdapter
{
/**
* Constructor
*
* Sets check flag to false.
*/
public function __construct()
{
$this->setLength(5);
$this->setCharacters('0123456789');
$this->useChecksum(false);
}
}

View File

@@ -0,0 +1,40 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Ean8 extends AbstractAdapter
{
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength([7, 8]);
$this->setCharacters('0123456789');
$this->setChecksum('gtin');
}
/**
* Overrides parent checkLength
*
* @param string $value Value
* @return bool
*/
public function hasValidLength($value)
{
if (strlen($value) == 7) {
$this->useChecksum(false);
} else {
$this->useChecksum(true);
}
return parent::hasValidLength($value);
}
}

View File

@@ -0,0 +1,23 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Gtin12 extends AbstractAdapter
{
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength(12);
$this->setCharacters('0123456789');
$this->setChecksum('gtin');
}
}

View File

@@ -0,0 +1,23 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Gtin13 extends AbstractAdapter
{
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength(13);
$this->setCharacters('0123456789');
$this->setChecksum('gtin');
}
}

View File

@@ -0,0 +1,23 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Gtin14 extends AbstractAdapter
{
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength(14);
$this->setCharacters('0123456789');
$this->setChecksum('gtin');
}
}

View File

@@ -0,0 +1,41 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Identcode extends AbstractAdapter
{
/**
* Allowed barcode lengths
* @var int
*/
protected $length = 12;
/**
* Allowed barcode characters
* @var string
*/
protected $characters = '0123456789';
/**
* Checksum function
* @var string
*/
protected $checksum = 'identcode';
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength(12);
$this->setCharacters('0123456789');
$this->setChecksum('identcode');
}
}

View File

@@ -0,0 +1,25 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Intelligentmail extends AbstractAdapter
{
/**
* Constructor
*
* Sets check flag to false.
*/
public function __construct()
{
$this->setLength([20, 25, 29, 31]);
$this->setCharacters('0123456789');
$this->useChecksum(false);
}
}

View File

@@ -0,0 +1,90 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Issn extends AbstractAdapter
{
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength([8, 13]);
$this->setCharacters('0123456789X');
$this->setChecksum('gtin');
}
/**
* Allows X on length of 8 chars
*
* @param string $value The barcode to check for allowed characters
* @return bool
*/
public function hasValidCharacters($value)
{
if (strlen($value) != 8) {
if (strpos($value, 'X') !== false) {
return false;
}
}
return parent::hasValidCharacters($value);
}
/**
* Validates the checksum
*
* @param string $value The barcode to check the checksum for
* @return bool
*/
public function hasValidChecksum($value)
{
if (strlen($value) == 8) {
$this->setChecksum('issn');
} else {
$this->setChecksum('gtin');
}
return parent::hasValidChecksum($value);
}
/**
* Validates the checksum ()
* ISSN implementation (reversed mod11)
*
* @param string $value The barcode to validate
* @return bool
*/
protected function issn($value)
{
$checksum = substr($value, -1, 1);
$values = str_split(substr($value, 0, -1));
$check = 0;
$multi = 8;
foreach ($values as $token) {
if ($token == 'X') {
$token = 10;
}
$check += ($token * $multi);
--$multi;
}
$check %= 11;
$check = ($check === 0 ? 0 : (11 - $check));
if ($check == $checksum) {
return true;
} elseif (($check == 10) && ($checksum == 'X')) {
return true;
}
return false;
}
}

View File

@@ -0,0 +1,23 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Itf14 extends AbstractAdapter
{
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength(14);
$this->setCharacters('0123456789');
$this->setChecksum('gtin');
}
}

View File

@@ -0,0 +1,23 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Leitcode extends AbstractAdapter
{
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength(14);
$this->setCharacters('0123456789');
$this->setChecksum('identcode');
}
}

View File

@@ -0,0 +1,23 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Planet extends AbstractAdapter
{
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength([12, 14]);
$this->setCharacters('0123456789');
$this->setChecksum('postnet');
}
}

View File

@@ -0,0 +1,23 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Postnet extends AbstractAdapter
{
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength([6, 7, 10, 12]);
$this->setCharacters('0123456789');
$this->setChecksum('postnet');
}
}

View File

@@ -0,0 +1,93 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Royalmail extends AbstractAdapter
{
protected $rows = [
'0' => 1, '1' => 1, '2' => 1, '3' => 1, '4' => 1, '5' => 1,
'6' => 2, '7' => 2, '8' => 2, '9' => 2, 'A' => 2, 'B' => 2,
'C' => 3, 'D' => 3, 'E' => 3, 'F' => 3, 'G' => 3, 'H' => 3,
'I' => 4, 'J' => 4, 'K' => 4, 'L' => 4, 'M' => 4, 'N' => 4,
'O' => 5, 'P' => 5, 'Q' => 5, 'R' => 5, 'S' => 5, 'T' => 5,
'U' => 0, 'V' => 0, 'W' => 0, 'X' => 0, 'Y' => 0, 'Z' => 0,
];
protected $columns = [
'0' => 1, '1' => 2, '2' => 3, '3' => 4, '4' => 5, '5' => 0,
'6' => 1, '7' => 2, '8' => 3, '9' => 4, 'A' => 5, 'B' => 0,
'C' => 1, 'D' => 2, 'E' => 3, 'F' => 4, 'G' => 5, 'H' => 0,
'I' => 1, 'J' => 2, 'K' => 3, 'L' => 4, 'M' => 5, 'N' => 0,
'O' => 1, 'P' => 2, 'Q' => 3, 'R' => 4, 'S' => 5, 'T' => 0,
'U' => 1, 'V' => 2, 'W' => 3, 'X' => 4, 'Y' => 5, 'Z' => 0,
];
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength(-1);
$this->setCharacters('0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ');
$this->setChecksum('royalmail');
}
/**
* Validates the checksum ()
*
* @param string $value The barcode to validate
* @return bool
*/
protected function royalmail($value)
{
$checksum = substr($value, -1, 1);
$values = str_split(substr($value, 0, -1));
$rowvalue = 0;
$colvalue = 0;
foreach ($values as $row) {
$rowvalue += $this->rows[$row];
$colvalue += $this->columns[$row];
}
$rowvalue %= 6;
$colvalue %= 6;
$rowchkvalue = array_keys($this->rows, $rowvalue);
$colchkvalue = array_keys($this->columns, $colvalue);
$intersect = array_intersect($rowchkvalue, $colchkvalue);
$chkvalue = current($intersect);
if ($chkvalue == $checksum) {
return true;
}
return false;
}
/**
* Allows start and stop tag within checked chars
*
* @param string $value The barcode to check for allowed characters
* @return bool
*/
public function hasValidCharacters($value)
{
if ($value[0] == '(') {
$value = substr($value, 1);
if ($value[strlen($value) - 1] == ')') {
$value = substr($value, 0, -1);
} else {
return false;
}
}
return parent::hasValidCharacters($value);
}
}

View File

@@ -0,0 +1,23 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Sscc extends AbstractAdapter
{
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength(18);
$this->setCharacters('0123456789');
$this->setChecksum('gtin');
}
}

View File

@@ -0,0 +1,23 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Upca extends AbstractAdapter
{
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength(12);
$this->setCharacters('0123456789');
$this->setChecksum('gtin');
}
}

View File

@@ -0,0 +1,40 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator\Barcode;
class Upce extends AbstractAdapter
{
/**
* Constructor for this barcode adapter
*/
public function __construct()
{
$this->setLength([6, 7, 8]);
$this->setCharacters('0123456789');
$this->setChecksum('gtin');
}
/**
* Overrides parent checkLength
*
* @param string $value Value
* @return bool
*/
public function hasValidLength($value)
{
if (strlen($value) != 8) {
$this->useChecksum(false);
} else {
$this->useChecksum(true);
}
return parent::hasValidLength($value);
}
}

View File

@@ -0,0 +1,181 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator;
use Traversable;
use Zend\Stdlib\ArrayUtils;
class Between extends AbstractValidator
{
const NOT_BETWEEN = 'notBetween';
const NOT_BETWEEN_STRICT = 'notBetweenStrict';
/**
* Validation failure message template definitions
*
* @var array
*/
protected $messageTemplates = [
self::NOT_BETWEEN => "The input is not between '%min%' and '%max%', inclusively",
self::NOT_BETWEEN_STRICT => "The input is not strictly between '%min%' and '%max%'"
];
/**
* Additional variables available for validation failure messages
*
* @var array
*/
protected $messageVariables = [
'min' => ['options' => 'min'],
'max' => ['options' => 'max'],
];
/**
* Options for the between validator
*
* @var array
*/
protected $options = [
'inclusive' => true, // Whether to do inclusive comparisons, allowing equivalence to min and/or max
'min' => 0,
'max' => PHP_INT_MAX,
];
/**
* Sets validator options
* Accepts the following option keys:
* 'min' => scalar, minimum border
* 'max' => scalar, maximum border
* 'inclusive' => boolean, inclusive border values
*
* @param array|Traversable $options
*
* @throws Exception\InvalidArgumentException
*/
public function __construct($options = null)
{
if ($options instanceof Traversable) {
$options = ArrayUtils::iteratorToArray($options);
}
if (!is_array($options)) {
$options = func_get_args();
$temp['min'] = array_shift($options);
if (!empty($options)) {
$temp['max'] = array_shift($options);
}
if (!empty($options)) {
$temp['inclusive'] = array_shift($options);
}
$options = $temp;
}
if (count($options) !== 2
&& (!array_key_exists('min', $options) || !array_key_exists('max', $options))
) {
throw new Exception\InvalidArgumentException("Missing option. 'min' and 'max' have to be given");
}
parent::__construct($options);
}
/**
* Returns the min option
*
* @return mixed
*/
public function getMin()
{
return $this->options['min'];
}
/**
* Sets the min option
*
* @param mixed $min
* @return Between Provides a fluent interface
*/
public function setMin($min)
{
$this->options['min'] = $min;
return $this;
}
/**
* Returns the max option
*
* @return mixed
*/
public function getMax()
{
return $this->options['max'];
}
/**
* Sets the max option
*
* @param mixed $max
* @return Between Provides a fluent interface
*/
public function setMax($max)
{
$this->options['max'] = $max;
return $this;
}
/**
* Returns the inclusive option
*
* @return bool
*/
public function getInclusive()
{
return $this->options['inclusive'];
}
/**
* Sets the inclusive option
*
* @param bool $inclusive
* @return Between Provides a fluent interface
*/
public function setInclusive($inclusive)
{
$this->options['inclusive'] = $inclusive;
return $this;
}
/**
* Returns true if and only if $value is between min and max options, inclusively
* if inclusive option is true.
*
* @param mixed $value
* @return bool
*/
public function isValid($value)
{
$this->setValue($value);
if ($this->getInclusive()) {
if ($this->getMin() > $value || $value > $this->getMax()) {
$this->error(self::NOT_BETWEEN);
return false;
}
} else {
if ($this->getMin() >= $value || $value >= $this->getMax()) {
$this->error(self::NOT_BETWEEN_STRICT);
return false;
}
}
return true;
}
}

View File

@@ -0,0 +1,192 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator;
use Traversable;
class Bitwise extends AbstractValidator
{
const OP_AND = 'and';
const OP_XOR = 'xor';
const NOT_AND = 'notAnd';
const NOT_AND_STRICT = 'notAndStrict';
const NOT_XOR = 'notXor';
/**
* @var integer
*/
protected $control;
/**
* Validation failure message template definitions
*
* @var array
*/
protected $messageTemplates = [
self::NOT_AND => "The input has no common bit set with '%control%'",
self::NOT_AND_STRICT => "The input doesn't have the same bits set as '%control%'",
self::NOT_XOR => "The input has common bit set with '%control%'",
];
/**
* Additional variables available for validation failure messages
*
* @var array
*/
protected $messageVariables = [
'control' => 'control',
];
/**
* @var integer
*/
protected $operator;
/**
* @var boolean
*/
protected $strict = false;
/**
* Sets validator options
* Accepts the following option keys:
* 'control' => integer
* 'operator' =>
* 'strict' => boolean
*
* @param array|Traversable $options
*/
public function __construct($options = null)
{
if ($options instanceof Traversable) {
$options = iterator_to_array($options);
}
if (!is_array($options)) {
$options = func_get_args();
$temp['control'] = array_shift($options);
if (!empty($options)) {
$temp['operator'] = array_shift($options);
}
if (!empty($options)) {
$temp['strict'] = array_shift($options);
}
$options = $temp;
}
parent::__construct($options);
}
/**
* Returns the control parameter.
*
* @return integer
*/
public function getControl()
{
return $this->control;
}
/**
* Returns the operator parameter.
*
* @return string
*/
public function getOperator()
{
return $this->operator;
}
/**
* Returns the strict parameter.
*
* @return boolean
*/
public function getStrict()
{
return $this->strict;
}
/**
* Returns true if and only if $value is between min and max options, inclusively
* if inclusive option is true.
*
* @param mixed $value
* @return bool
*/
public function isValid($value)
{
$this->setValue($value);
if (self::OP_AND === $this->operator) {
if ($this->strict) {
// All the bits set in value must be set in control
$this->error(self::NOT_AND_STRICT);
return (bool) (($this->control & $value) == $value);
} else {
// At least one of the bits must be common between value and control
$this->error(self::NOT_AND);
return (bool) ($this->control & $value);
}
} elseif (self::OP_XOR === $this->operator) {
$this->error(self::NOT_XOR);
return (bool) (($this->control ^ $value) === ($this->control | $value));
}
return false;
}
/**
* Sets the control parameter.
*
* @param integer $control
* @return Bitwise
*/
public function setControl($control)
{
$this->control = (int) $control;
return $this;
}
/**
* Sets the operator parameter.
*
* @param string $operator
* @return Bitwise
*/
public function setOperator($operator)
{
$this->operator = $operator;
return $this;
}
/**
* Sets the strict parameter.
*
* @param boolean $strict
* @return Bitwise
*/
public function setStrict($strict)
{
$this->strict = (bool) $strict;
return $this;
}
}

View File

@@ -0,0 +1,150 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator;
class Callback extends AbstractValidator
{
/**
* Invalid callback
*/
const INVALID_CALLBACK = 'callbackInvalid';
/**
* Invalid value
*/
const INVALID_VALUE = 'callbackValue';
/**
* Validation failure message template definitions
*
* @var array
*/
protected $messageTemplates = [
self::INVALID_VALUE => "The input is not valid",
self::INVALID_CALLBACK => "An exception has been raised within the callback",
];
/**
* Default options to set for the validator
*
* @var mixed
*/
protected $options = [
'callback' => null, // Callback in a call_user_func format, string || array
'callbackOptions' => [], // Options for the callback
];
/**
* Constructor
*
* @param array|callable $options
*/
public function __construct($options = null)
{
if (is_callable($options)) {
$options = ['callback' => $options];
}
parent::__construct($options);
}
/**
* Returns the set callback
*
* @return mixed
*/
public function getCallback()
{
return $this->options['callback'];
}
/**
* Sets the callback
*
* @param string|array|callable $callback
* @return Callback Provides a fluent interface
* @throws Exception\InvalidArgumentException
*/
public function setCallback($callback)
{
if (!is_callable($callback)) {
throw new Exception\InvalidArgumentException('Invalid callback given');
}
$this->options['callback'] = $callback;
return $this;
}
/**
* Returns the set options for the callback
*
* @return mixed
*/
public function getCallbackOptions()
{
return $this->options['callbackOptions'];
}
/**
* Sets options for the callback
*
* @param mixed $options
* @return Callback Provides a fluent interface
*/
public function setCallbackOptions($options)
{
$this->options['callbackOptions'] = (array) $options;
return $this;
}
/**
* Returns true if and only if the set callback returns
* for the provided $value
*
* @param mixed $value
* @param mixed $context Additional context to provide to the callback
* @return bool
* @throws Exception\InvalidArgumentException
*/
public function isValid($value, $context = null)
{
$this->setValue($value);
$options = $this->getCallbackOptions();
$callback = $this->getCallback();
if (empty($callback)) {
throw new Exception\InvalidArgumentException('No callback given');
}
$args = [$value];
if (empty($options) && !empty($context)) {
$args[] = $context;
}
if (!empty($options) && empty($context)) {
$args = array_merge($args, $options);
}
if (!empty($options) && !empty($context)) {
$args[] = $context;
$args = array_merge($args, $options);
}
try {
if (!call_user_func_array($callback, $args)) {
$this->error(self::INVALID_VALUE);
return false;
}
} catch (\Exception $e) {
$this->error(self::INVALID_CALLBACK);
return false;
}
return true;
}
}

View File

@@ -0,0 +1,37 @@
<?php
/**
* @link http://github.com/zendframework/zend-validator for the canonical source repository
* @copyright Copyright (c) 2005-2016 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator;
class ConfigProvider
{
/**
* Return configuration for this component.
*
* @return array
*/
public function __invoke()
{
return [
'dependencies' => $this->getDependencyConfig(),
];
}
/**
* Return dependency mappings for this component.
*
* @return array
*/
public function getDependencyConfig()
{
return [
'factories' => [
'ValidatorManager' => ValidatorPluginManagerFactory::class,
],
];
}
}

View File

@@ -0,0 +1,319 @@
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Validator;
use Traversable;
use Zend\Stdlib\ArrayUtils;
class CreditCard extends AbstractValidator
{
/**
* Detected CCI list
*
* @var string
*/
const ALL = 'All';
const AMERICAN_EXPRESS = 'American_Express';
const UNIONPAY = 'Unionpay';
const DINERS_CLUB = 'Diners_Club';
const DINERS_CLUB_US = 'Diners_Club_US';
const DISCOVER = 'Discover';
const JCB = 'JCB';
const LASER = 'Laser';
const MAESTRO = 'Maestro';
const MASTERCARD = 'Mastercard';
const SOLO = 'Solo';
const VISA = 'Visa';
const CHECKSUM = 'creditcardChecksum';
const CONTENT = 'creditcardContent';
const INVALID = 'creditcardInvalid';
const LENGTH = 'creditcardLength';
const PREFIX = 'creditcardPrefix';
const SERVICE = 'creditcardService';
const SERVICEFAILURE = 'creditcardServiceFailure';
/**
* Validation failure message template definitions
*
* @var array
*/
protected $messageTemplates = [
self::CHECKSUM => "The input seems to contain an invalid checksum",
self::CONTENT => "The input must contain only digits",
self::INVALID => "Invalid type given. String expected",
self::LENGTH => "The input contains an invalid amount of digits",
self::PREFIX => "The input is not from an allowed institute",
self::SERVICE => "The input seems to be an invalid credit card number",
self::SERVICEFAILURE => "An exception has been raised while validating the input",
];
/**
* List of CCV names
*
* @var array
*/
protected $cardName = [
0 => self::AMERICAN_EXPRESS,
1 => self::DINERS_CLUB,
2 => self::DINERS_CLUB_US,
3 => self::DISCOVER,
4 => self::JCB,
5 => self::LASER,
6 => self::MAESTRO,
7 => self::MASTERCARD,
8 => self::SOLO,
9 => self::UNIONPAY,
10 => self::VISA,
];
/**
* List of allowed CCV lengths
*
* @var array
*/
protected $cardLength = [
self::AMERICAN_EXPRESS => [15],
self::DINERS_CLUB => [14],
self::DINERS_CLUB_US => [16],
self::DISCOVER => [16],
self::JCB => [15, 16],
self::LASER => [16, 17, 18, 19],
self::MAESTRO => [12, 13, 14, 15, 16, 17, 18, 19],
self::MASTERCARD => [16],
self::SOLO => [16, 18, 19],
self::UNIONPAY => [16, 17, 18, 19],
self::VISA => [16],
];
/**
* List of accepted CCV provider tags
*
* @var array
*/
protected $cardType = [
self::AMERICAN_EXPRESS => ['34', '37'],
self::DINERS_CLUB => ['300', '301', '302', '303', '304', '305', '36'],
self::DINERS_CLUB_US => ['54', '55'],
self::DISCOVER => ['6011', '622126', '622127', '622128', '622129', '62213',
'62214', '62215', '62216', '62217', '62218', '62219',
'6222', '6223', '6224', '6225', '6226', '6227', '6228',
'62290', '62291', '622920', '622921', '622922', '622923',
'622924', '622925', '644', '645', '646', '647', '648',
'649', '65'],
self::JCB => ['1800', '2131', '3528', '3529', '353', '354', '355', '356', '357', '358'],
self::LASER => ['6304', '6706', '6771', '6709'],
self::MAESTRO => ['5018', '5020', '5038', '6304', '6759', '6761', '6762', '6763',
'6764', '6765', '6766', '6772'],
self::MASTERCARD => ['51', '52', '53', '54', '55'],
self::SOLO => ['6334', '6767'],
self::UNIONPAY => ['622126', '622127', '622128', '622129', '62213', '62214',
'62215', '62216', '62217', '62218', '62219', '6222', '6223',
'6224', '6225', '6226', '6227', '6228', '62290', '62291',
'622920', '622921', '622922', '622923', '622924', '622925'],
self::VISA => ['4'],
];
/**
* Options for this validator
*
* @var array
*/
protected $options = [
'service' => null, // Service callback for additional validation
'type' => [], // CCIs which are accepted by validation
];
/**
* Constructor
*
* @param string|array|Traversable $options OPTIONAL Type of CCI to allow
*/
public function __construct($options = [])
{
if ($options instanceof Traversable) {
$options = ArrayUtils::iteratorToArray($options);
} elseif (!is_array($options)) {
$options = func_get_args();
$temp['type'] = array_shift($options);
if (!empty($options)) {
$temp['service'] = array_shift($options);
}
$options = $temp;
}
if (!array_key_exists('type', $options)) {
$options['type'] = self::ALL;
}
$this->setType($options['type']);
unset($options['type']);
if (array_key_exists('service', $options)) {
$this->setService($options['service']);
unset($options['service']);
}
parent::__construct($options);
}
/**
* Returns a list of accepted CCIs
*
* @return array
*/
public function getType()
{
return $this->options['type'];
}
/**
* Sets CCIs which are accepted by validation
*
* @param string|array $type Type to allow for validation
* @return CreditCard Provides a fluid interface
*/
public function setType($type)
{
$this->options['type'] = [];
return $this->addType($type);
}
/**
* Adds a CCI to be accepted by validation
*
* @param string|array $type Type to allow for validation
* @return CreditCard Provides a fluid interface
*/
public function addType($type)
{
if (is_string($type)) {
$type = [$type];
}
foreach ($type as $typ) {
if (defined('self::' . strtoupper($typ)) && !in_array($typ, $this->options['type'])) {
$this->options['type'][] = $typ;
}
if (($typ == self::ALL)) {
$this->options['type'] = array_keys($this->cardLength);
}
}
return $this;
}
/**
* Returns the actual set service
*
* @return callable
*/
public function getService()
{
return $this->options['service'];
}
/**
* Sets a new callback for service validation
*
* @param callable $service
* @return CreditCard
* @throws Exception\InvalidArgumentException on invalid service callback
*/
public function setService($service)
{
if (!is_callable($service)) {
throw new Exception\InvalidArgumentException('Invalid callback given');
}
$this->options['service'] = $service;
return $this;
}
/**
* Returns true if and only if $value follows the Luhn algorithm (mod-10 checksum)
*
* @param string $value
* @return bool
*/
public function isValid($value)
{
$this->setValue($value);
if (!is_string($value)) {
$this->error(self::INVALID, $value);
return false;
}
if (!ctype_digit($value)) {
$this->error(self::CONTENT, $value);
return false;
}
$length = strlen($value);
$types = $this->getType();
$foundp = false;
$foundl = false;
foreach ($types as $type) {
foreach ($this->cardType[$type] as $prefix) {
if (substr($value, 0, strlen($prefix)) == $prefix) {
$foundp = true;
if (in_array($length, $this->cardLength[$type])) {
$foundl = true;
break 2;
}
}
}
}
if ($foundp == false) {
$this->error(self::PREFIX, $value);
return false;
}
if ($foundl == false) {
$this->error(self::LENGTH, $value);
return false;
}
$sum = 0;
$weight = 2;
for ($i = $length - 2; $i >= 0; $i--) {
$digit = $weight * $value[$i];
$sum += floor($digit / 10) + $digit % 10;
$weight = $weight % 2 + 1;
}
if ((10 - $sum % 10) % 10 != $value[$length - 1]) {
$this->error(self::CHECKSUM, $value);
return false;
}
$service = $this->getService();
if (!empty($service)) {
try {
$callback = new Callback($service);
$callback->setOptions($this->getType());
if (!$callback->isValid($value)) {
$this->error(self::SERVICE, $value);
return false;
}
} catch (\Exception $e) {
$this->error(self::SERVICEFAILURE, $value);
return false;
}
}
return true;
}
}

Some files were not shown because too many files have changed in this diff Show More