updated-packages
This commit is contained in:
180
vendor/zendframework/zend-validator/CHANGELOG.md
vendored
180
vendor/zendframework/zend-validator/CHANGELOG.md
vendored
@@ -2,6 +2,186 @@
|
||||
|
||||
All notable changes to this project will be documented in this file, in reverse chronological order by release.
|
||||
|
||||
## 2.13.0 - 2019-12-27
|
||||
|
||||
### Added
|
||||
|
||||
- [#275](https://github.com/zendframework/zend-validator/pull/275) adds a new `strict` option to `Zend\Validator\Date`; when `true`, the value being validated must both be a date AND in the same format as provided via the `format` option.
|
||||
|
||||
- [#264](https://github.com/zendframework/zend-validator/pull/264) adds `Zend\Validator\UndisclosedPassword`, which can be used to determine if a password has been exposed in a known data breach as reported on the [Have I Been Pwned?](https://www.haveibeenpwned.com) website. [Documentation](https://docs.zendframework.com/zend-validator/validators/undisclosed-password/)
|
||||
|
||||
- [#266](https://github.com/zendframework/zend-validator/pull/266) adds a new option to the `File\Extension` and `File\ExcludeExtension` validators, `allowNonExistentFile`. When set to `true`, the validators will continue validating the extension of the filename given even if the file does not exist. The default is `false`, to preserve backwards compatibility with previous versions.
|
||||
|
||||
### Changed
|
||||
|
||||
- [#264](https://github.com/zendframework/zend-validator/pull/264) bumps the minimum supported PHP version to 7.1.0.
|
||||
|
||||
- [#279](https://github.com/zendframework/zend-validator/pull/279) updates the `magic.mime` file used for file validations.
|
||||
|
||||
### Deprecated
|
||||
|
||||
- Nothing.
|
||||
|
||||
### Removed
|
||||
|
||||
- [#264](https://github.com/zendframework/zend-validator/pull/264) removes support for PHP versions prior to 7.1.0.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Nothing.
|
||||
|
||||
## 2.12.2 - 2019-10-29
|
||||
|
||||
### Added
|
||||
|
||||
- Nothing.
|
||||
|
||||
### Changed
|
||||
|
||||
- Nothing.
|
||||
|
||||
### Deprecated
|
||||
|
||||
- Nothing.
|
||||
|
||||
### Removed
|
||||
|
||||
- Nothing.
|
||||
|
||||
### Fixed
|
||||
|
||||
- [#277](https://github.com/zendframework/zend-validator/pull/277) fixes `File\Hash` validator in case
|
||||
when the file hash contains only digits.
|
||||
|
||||
- [#277](https://github.com/zendframework/zend-validator/pull/277) fixes `File\Hash` validator to match
|
||||
hash with the given hashing algorithm.
|
||||
|
||||
## 2.12.1 - 2019-10-12
|
||||
|
||||
### Added
|
||||
|
||||
- Nothing.
|
||||
|
||||
### Changed
|
||||
|
||||
- Nothing.
|
||||
|
||||
### Deprecated
|
||||
|
||||
- Nothing.
|
||||
|
||||
### Removed
|
||||
|
||||
- Nothing.
|
||||
|
||||
### Fixed
|
||||
|
||||
- [#272](https://github.com/zendframework/zend-validator/pull/272) changes
|
||||
curly braces in array and string offset access to square brackets
|
||||
in order to prevent issues under the upcoming PHP 7.4 release.
|
||||
|
||||
- [#231](https://github.com/zendframework/zend-validator/pull/231) fixes validation of input hashes in `Zend\Validator\File\Hash` validator when provided as array.
|
||||
Only string hashes are allowed. If different type is provided `Zend\Validator\Exception\InvalidArgumentException` is thrown.
|
||||
|
||||
## 2.12.0 - 2019-01-30
|
||||
|
||||
### Added
|
||||
|
||||
- [#250](https://github.com/zendframework/zend-validator/pull/250) adds support for PHP 7.3.
|
||||
|
||||
### Changed
|
||||
|
||||
- [#251](https://github.com/zendframework/zend-validator/pull/251) updates the logic of each of the various `Zend\Validator\File` validators
|
||||
to allow validating against PSR-7 `UploadedFileInterface` instances, expanding
|
||||
the support originally provided in version 2.11.0.
|
||||
|
||||
### Deprecated
|
||||
|
||||
- Nothing.
|
||||
|
||||
### Removed
|
||||
|
||||
- [#250](https://github.com/zendframework/zend-validator/pull/250) removes support for zend-stdlib v2 releases.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Nothing.
|
||||
|
||||
## 2.11.1 - 2019-01-29
|
||||
|
||||
### Added
|
||||
|
||||
- [#249](https://github.com/zendframework/zend-validator/pull/249) adds support in the hostname validator for the `.rs` TLD.
|
||||
|
||||
### Changed
|
||||
|
||||
- [#253](https://github.com/zendframework/zend-validator/pull/253) updates the list of allowed characters for a `DE` domain name to match those published by IDN.
|
||||
|
||||
### Deprecated
|
||||
|
||||
- Nothing.
|
||||
|
||||
### Removed
|
||||
|
||||
- Nothing.
|
||||
|
||||
### Fixed
|
||||
|
||||
- [#256](https://github.com/zendframework/zend-validator/pull/256) fixes hostname validation when omitting the TLD from verification,
|
||||
ensuring validation of the domain segment considers all URI criteria.
|
||||
|
||||
## 2.11.0 - 2018-12-13
|
||||
|
||||
### Added
|
||||
|
||||
- [#237](https://github.com/zendframework/zend-validator/pull/237) adds support for the [PSR-7 UploadedFileInterface](https://www.php-fig.org/psr/psr-7/#uploadedfileinterface)
|
||||
to each of the `Upload` and `UploadFile` validators.
|
||||
|
||||
- [#220](https://github.com/zendframework/zend-validator/pull/220) adds image/webp to the list of known image types for the `IsImage` validator.
|
||||
|
||||
### Changed
|
||||
|
||||
- Nothing.
|
||||
|
||||
### Deprecated
|
||||
|
||||
- Nothing.
|
||||
|
||||
### Removed
|
||||
|
||||
- Nothing.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Nothing.
|
||||
|
||||
## 2.10.3 - 2018-12-13
|
||||
|
||||
### Added
|
||||
|
||||
- Nothing.
|
||||
|
||||
### Changed
|
||||
|
||||
- Nothing.
|
||||
|
||||
### Deprecated
|
||||
|
||||
- Nothing.
|
||||
|
||||
### Removed
|
||||
|
||||
- Nothing.
|
||||
|
||||
### Fixed
|
||||
|
||||
- [#241](https://github.com/zendframework/zend-validator/pull/241) has the `Hostname` validator return an invalid result early when an empty
|
||||
domain segment is detected.
|
||||
|
||||
- [#232](https://github.com/zendframework/zend-validator/pull/232) updates the `Hostname` validator to allow underscores in subdomains.
|
||||
|
||||
- [#218](https://github.com/zendframework/zend-validator/pull/218) fixes a precision issue with the `Step` validator.
|
||||
|
||||
## 2.10.2 - 2018-02-01
|
||||
|
||||
### Added
|
||||
|
43
vendor/zendframework/zend-validator/CONDUCT.md
vendored
43
vendor/zendframework/zend-validator/CONDUCT.md
vendored
@@ -1,43 +0,0 @@
|
||||
# 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 everyone’s 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.
|
234
vendor/zendframework/zend-validator/CONTRIBUTING.md
vendored
234
vendor/zendframework/zend-validator/CONTRIBUTING.md
vendored
@@ -1,234 +0,0 @@
|
||||
# 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 [phpcs](https://github.com/squizlabs/PHP_CodeSniffer) for coding
|
||||
standards checks, and provides configuration for our selected checks.
|
||||
`phpcs` is installed by default via Composer.
|
||||
|
||||
To run checks only:
|
||||
|
||||
```console
|
||||
$ composer cs-check
|
||||
```
|
||||
|
||||
`phpcs` also includes a tool for fixing most CS violations, `phpcbf`:
|
||||
|
||||
|
||||
```console
|
||||
$ composer cs-fix
|
||||
```
|
||||
|
||||
If you allow `phpcbf` 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.
|
13
vendor/zendframework/zend-validator/LICENSE.md
vendored
13
vendor/zendframework/zend-validator/LICENSE.md
vendored
@@ -1,16 +1,15 @@
|
||||
Copyright (c) 2005-2015, Zend Technologies USA, Inc.
|
||||
|
||||
Copyright (c) 2005-2019, 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 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.
|
||||
- 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
|
||||
|
21
vendor/zendframework/zend-validator/README.md
vendored
21
vendor/zendframework/zend-validator/README.md
vendored
@@ -1,11 +1,26 @@
|
||||
# zend-validator
|
||||
|
||||
[](https://secure.travis-ci.org/zendframework/zend-validator)
|
||||
[](https://coveralls.io/r/zendframework/zend-validator?branch=master)
|
||||
[](https://coveralls.io/github/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/
|
||||
## Installation
|
||||
|
||||
Run the following to install this library:
|
||||
|
||||
```bash
|
||||
$ composer require zendframework/zend-validator
|
||||
```
|
||||
|
||||
## Documentation
|
||||
|
||||
Browse the documentation online at https://docs.zendframework.com/zend-validator/
|
||||
|
||||
## Support
|
||||
|
||||
* [Issues](https://github.com/zendframework/zend-validator/issues/)
|
||||
* [Chat](https://zendframework-slack.herokuapp.com/)
|
||||
* [Forum](https://discourse.zendframework.com/)
|
||||
|
@@ -1,24 +1,32 @@
|
||||
{
|
||||
"name": "zendframework/zend-validator",
|
||||
"description": "provides a set of commonly needed validators",
|
||||
"description": "Validation classes for a wide range of domains, and the ability to chain validators to create complex validation criteria",
|
||||
"license": "BSD-3-Clause",
|
||||
"keywords": [
|
||||
"zf2",
|
||||
"zendframework",
|
||||
"zf",
|
||||
"validator"
|
||||
],
|
||||
"homepage": "https://github.com/zendframework/zend-validator",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Zend\\Validator\\": "src/"
|
||||
}
|
||||
"support": {
|
||||
"docs": "https://docs.zendframework.com/zend-validator/",
|
||||
"issues": "https://github.com/zendframework/zend-validator/issues",
|
||||
"source": "https://github.com/zendframework/zend-validator",
|
||||
"rss": "https://github.com/zendframework/zend-validator/releases.atom",
|
||||
"chat": "https://zendframework-slack.herokuapp.com",
|
||||
"forum": "https://discourse.zendframework.com/c/questions/components"
|
||||
},
|
||||
"require": {
|
||||
"php": "^5.6 || ^7.0",
|
||||
"zendframework/zend-stdlib": "^2.7.6 || ^3.1",
|
||||
"php": "^7.1",
|
||||
"zendframework/zend-stdlib": "^3.2.1",
|
||||
"container-interop/container-interop": "^1.1"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^6.0.8 || ^5.7.15",
|
||||
"psr/http-message": "^1.0",
|
||||
"psr/http-client": "^1.0",
|
||||
"psr/http-factory": "^1.0",
|
||||
"zendframework/zend-cache": "^2.6.1",
|
||||
"zendframework/zend-coding-standard": "~1.0.0",
|
||||
"zendframework/zend-config": "^2.6",
|
||||
"zendframework/zend-db": "^2.7",
|
||||
"zendframework/zend-filter": "^2.6",
|
||||
@@ -27,11 +35,10 @@
|
||||
"zendframework/zend-math": "^2.6",
|
||||
"zendframework/zend-servicemanager": "^2.7.5 || ^3.0.3",
|
||||
"zendframework/zend-session": "^2.8",
|
||||
"zendframework/zend-uri": "^2.5",
|
||||
"phpunit/PHPUnit": "^6.0.8 || ^5.7.15",
|
||||
"zendframework/zend-coding-standard": "~1.0.0"
|
||||
"zendframework/zend-uri": "^2.5"
|
||||
},
|
||||
"suggest": {
|
||||
"psr/http-message": "psr/http-message, required when validating PSR-7 UploadedFileInterface instances via the Upload and UploadFile validators",
|
||||
"zendframework/zend-db": "Zend\\Db component, required by the (No)RecordExists validator",
|
||||
"zendframework/zend-filter": "Zend\\Filter component, required by the Digits validator",
|
||||
"zendframework/zend-i18n": "Zend\\I18n component to allow translation of validation error messages",
|
||||
@@ -41,16 +48,9 @@
|
||||
"zendframework/zend-session": "Zend\\Session component, ^2.8; required by the Csrf validator",
|
||||
"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.10.x-dev",
|
||||
"dev-develop": "2.11.x-dev"
|
||||
},
|
||||
"zf": {
|
||||
"component": "Zend\\Validator",
|
||||
"config-provider": "Zend\\Validator\\ConfigProvider"
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Zend\\Validator\\": "src/"
|
||||
}
|
||||
},
|
||||
"autoload-dev": {
|
||||
@@ -58,6 +58,19 @@
|
||||
"ZendTest\\Validator\\": "test/"
|
||||
}
|
||||
},
|
||||
"config": {
|
||||
"sort-packages": true
|
||||
},
|
||||
"extra": {
|
||||
"branch-alias": {
|
||||
"dev-master": "2.13.x-dev",
|
||||
"dev-develop": "2.14.x-dev"
|
||||
},
|
||||
"zf": {
|
||||
"component": "Zend\\Validator",
|
||||
"config-provider": "Zend\\Validator\\ConfigProvider"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"check": [
|
||||
"@cs-check",
|
||||
|
2293
vendor/zendframework/zend-validator/composer.lock
generated
vendored
2293
vendor/zendframework/zend-validator/composer.lock
generated
vendored
File diff suppressed because it is too large
Load Diff
@@ -1,12 +0,0 @@
|
||||
<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>
|
||||
|
@@ -1 +0,0 @@
|
||||
../../README.md
|
@@ -1,213 +0,0 @@
|
||||
# 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.
|
@@ -1,108 +0,0 @@
|
||||
# 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`.
|
@@ -1,44 +0,0 @@
|
||||
# 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)
|
||||
- [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`.
|
@@ -1,96 +0,0 @@
|
||||
# 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
|
||||
```
|
@@ -1,358 +0,0 @@
|
||||
# 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
|
||||
}
|
||||
```
|
@@ -1,54 +0,0 @@
|
||||
# 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`.
|
@@ -1,203 +0,0 @@
|
||||
# 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.
|
@@ -1,173 +0,0 @@
|
||||
# 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
|
||||
- Russia Mir
|
||||
|
||||
> ### 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.
|
@@ -1,35 +0,0 @@
|
||||
# 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 [DateTime::createFromFormat()](http://php.net/manual/en/datetime.createfromformat.php#refsect1-datetime.createfromformat-parameters) method.
|
||||
|
||||
```php
|
||||
$validator = new Zend\Validator\Date(['format' => 'Y']);
|
||||
|
||||
$validator->isValid('2010'); // returns true
|
||||
$validator->isValid('May'); // returns false
|
||||
```
|
@@ -1,180 +0,0 @@
|
||||
# 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.
|
@@ -1,27 +0,0 @@
|
||||
# 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`.
|
@@ -1,206 +0,0 @@
|
||||
# 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 hostnameValidator option to set the hostname validator.
|
||||
Possible values of this option defined in [Hostname](hostname.md) validator's
|
||||
`ALLOW_*` constants:
|
||||
- `ALLOW_DNS` (default) - Allows Internet domain names _(e.g. example.com)_
|
||||
- `ALLOW_IP` - Allows IP addresses _(e.g. 192.168.0.1)_
|
||||
- `ALLOW_LOCAL` - Allows local network such as _localhost_ or _www.localdomain_
|
||||
- `ALLOW_URI` - Allows hostnames in URI generic syntax. See [RFC 3986](https://www.ietf.org/rfc/rfc3986.txt)
|
||||
- `ALLOW_ALL` - Allows all types of hostnames
|
||||
|
||||
- `useDeepMxCheck`: 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`.
|
||||
- `useDomainCheck`: 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`.
|
||||
- `hostnameValidator`: Sets the hostname validator object instance with which the
|
||||
domain part of the email address will be validated.
|
||||
- `useMxCheck`: 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'
|
||||
]);
|
||||
```
|
@@ -1,48 +0,0 @@
|
||||
# Explode Validator
|
||||
|
||||
`Zend\Validator\Explode` executes a validator for each item exploded from an
|
||||
array.
|
||||
|
||||
## Supported options
|
||||
|
||||
The following options are supported for `Zend\Validator\Explode`:
|
||||
|
||||
- `valueDelimiter`: Defines the delimiter used to explode values from an array.
|
||||
It defaults to `,`. If the given value is an array, this option isn't used.
|
||||
- `validator`: Sets the validator that will be executed on each exploded item.
|
||||
This may be a validator instance, or a validator service name.
|
||||
|
||||
## Basic usage
|
||||
|
||||
To validate if every item in an array is in a specified haystack:
|
||||
|
||||
```php
|
||||
$inArrayValidator = new Zend\Validator\InArray([
|
||||
'haystack' => [1, 2, 3, 4, 5, 6],
|
||||
]);
|
||||
|
||||
$explodeValidator = new Zend\Validator\Explode([
|
||||
'validator' => $inArrayValidator
|
||||
]);
|
||||
|
||||
$explodeValidator->isValid([1, 4, 6]); // returns true
|
||||
$explodeValidator->isValid([1, 4, 6, 8]); // returns false
|
||||
```
|
||||
|
||||
## Exploding strings
|
||||
|
||||
To validate if every e-mail in a string is contained in a list of names:
|
||||
|
||||
```php
|
||||
$inEmailListValidator = new Zend\Validator\InArray([
|
||||
'haystack' => ['joseph@test.com', 'mark@test.com', 'lucia@test.com'],
|
||||
]);
|
||||
|
||||
$explodeValidator = new Zend\Validator\Explode([
|
||||
'validator' => $inEmailListValidator,
|
||||
'valueDelimiter' => ','
|
||||
]);
|
||||
|
||||
$explodeValidator->isValid('joseph@test.com,mark@test.com'); // returns true
|
||||
$explodeValidator->isValid('lucia@test.com,maria@test.com'); // returns false
|
||||
```
|
@@ -1,31 +0,0 @@
|
||||
# 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!
|
||||
}
|
||||
```
|
@@ -1,60 +0,0 @@
|
||||
# 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(['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.
|
@@ -1,7 +0,0 @@
|
||||
# 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.
|
@@ -1,9 +0,0 @@
|
||||
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.
|
@@ -1,35 +0,0 @@
|
||||
# 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.
|
@@ -1,52 +0,0 @@
|
||||
# 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.
|
@@ -1,38 +0,0 @@
|
||||
# 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
|
||||
}
|
||||
```
|
@@ -1,66 +0,0 @@
|
||||
# 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.
|
@@ -1,71 +0,0 @@
|
||||
# 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`.
|
@@ -1,30 +0,0 @@
|
||||
# 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.
|
@@ -1,21 +0,0 @@
|
||||
# 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
|
||||
}
|
||||
```
|
@@ -1,21 +0,0 @@
|
||||
# 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
|
||||
}
|
||||
```
|
@@ -1,68 +0,0 @@
|
||||
# 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.
|
@@ -1,68 +0,0 @@
|
||||
# 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.
|
@@ -1,42 +0,0 @@
|
||||
# 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.
|
@@ -1,69 +0,0 @@
|
||||
# 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.
|
@@ -1,37 +0,0 @@
|
||||
# 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
|
||||
}
|
||||
```
|
@@ -1,25 +0,0 @@
|
||||
# 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.
|
@@ -1,30 +0,0 @@
|
||||
# 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
|
||||
}
|
||||
```
|
@@ -1,34 +0,0 @@
|
||||
# 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
|
||||
}
|
||||
```
|
@@ -1,48 +0,0 @@
|
||||
# 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`.
|
@@ -1,25 +0,0 @@
|
||||
# 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`.
|
@@ -1,142 +0,0 @@
|
||||
# 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.
|
@@ -1,55 +0,0 @@
|
||||
# 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
|
||||
}
|
||||
```
|
@@ -1,239 +0,0 @@
|
||||
# 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' => [
|
||||
[
|
||||
'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' => [
|
||||
[
|
||||
'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.
|
@@ -1,161 +0,0 @@
|
||||
# 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' => ['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' => [
|
||||
'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.
|
@@ -1,66 +0,0 @@
|
||||
# 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.
|
@@ -1,107 +0,0 @@
|
||||
# IsCountable Validator
|
||||
|
||||
- **Since 2.10.0**
|
||||
|
||||
`Zend\Validator\IsCountable` allows you to validate that a value can be counted
|
||||
(i.e., it's an array or implements `Countable`), and, optionally:
|
||||
|
||||
- the exact count of the value
|
||||
- the minimum count of the value
|
||||
- the maximum count of the value
|
||||
|
||||
Specifying either of the latter two is inconsistent with the first, and, as
|
||||
such, the validator does not allow setting both a count and a minimum or maximum
|
||||
value. You may, however specify both minimum and maximum values, in which case
|
||||
the validator operates similar to the [Between validator](between.md).
|
||||
|
||||
## Supported options
|
||||
|
||||
The following options are supported for `Zend\Validator\IsCountable`:
|
||||
|
||||
- `count`: Defines if the validation should look for a specific, exact count for
|
||||
the value provided.
|
||||
- `max`: Sets the maximum value for the validation; if the count of the value is
|
||||
greater than the maximum, validation fails..
|
||||
- `min`: Sets the minimum value for the validation; if the count of the value is
|
||||
lower than the minimum, validation fails.
|
||||
|
||||
## Default behaviour
|
||||
|
||||
Given no options, the validator simply tests to see that the value may be
|
||||
counted (i.e., it's an array or `Countable` instance):
|
||||
|
||||
```php
|
||||
$validator = new Zend\Validator\IsCountable();
|
||||
|
||||
$validator->isValid(10); // false; not an array or Countable
|
||||
$validator->isValid([10]); // true; value is an array
|
||||
$validator->isValid(new ArrayObject([10])); // true; value is Countable
|
||||
$validator->isValid(new stdClass); // false; value is not Countable
|
||||
```
|
||||
|
||||
## Specifying an exact count
|
||||
|
||||
You can also specify an exact count; if the value is countable, and its count
|
||||
matches, the the value is valid.
|
||||
|
||||
```php
|
||||
$validator = new Zend\Validator\IsCountable(['count' => 3]);
|
||||
|
||||
$validator->isValid([1, 2, 3]); // true; countable, and count is 3
|
||||
$validator->isValid(new ArrayObject([1, 2, 3])); // true; countable, and count is 3
|
||||
$validator->isValid([1]); // false; countable, but count is 1
|
||||
$validator->isValid(new ArrayObject([1])); // false; countable, but count is 1
|
||||
```
|
||||
|
||||
## Specifying a minimum count
|
||||
|
||||
You may specify a minimum count. When you do, the value must be countable, and
|
||||
greater than or equal to the minimum count you specify in order to be valid.
|
||||
|
||||
```php
|
||||
$validator = new Zend\Validator\IsCountable(['min' => 2]);
|
||||
|
||||
$validator->isValid([1, 2, 3]); // true; countable, and count is 3
|
||||
$validator->isValid(new ArrayObject([1, 2, 3])); // true; countable, and count is 3
|
||||
$validator->isValid([1, 2]); // true; countable, and count is 2
|
||||
$validator->isValid(new ArrayObject([1, 2])); // true; countable, and count is 2
|
||||
$validator->isValid([1]); // false; countable, but count is 1
|
||||
$validator->isValid(new ArrayObject([1])); // false; countable, but count is 1
|
||||
```
|
||||
|
||||
## Specifying a maximum count
|
||||
|
||||
You may specify a maximum count. When you do, the value must be countable, and
|
||||
less than or equal to the maximum count you specify in order to be valid.
|
||||
|
||||
```php
|
||||
$validator = new Zend\Validator\IsCountable(['max' => 2]);
|
||||
|
||||
$validator->isValid([1, 2, 3]); // false; countable, but count is 3
|
||||
$validator->isValid(new ArrayObject([1, 2, 3])); // false; countable, but count is 3
|
||||
$validator->isValid([1, 2]); // true; countable, and count is 2
|
||||
$validator->isValid(new ArrayObject([1, 2])); // true; countable, and count is 2
|
||||
$validator->isValid([1]); // true; countable, and count is 1
|
||||
$validator->isValid(new ArrayObject([1])); // true; countable, and count is 1
|
||||
```
|
||||
|
||||
## Specifying both minimum and maximum
|
||||
|
||||
If you specify both a minimum and maximum, the count must be _between_ the two,
|
||||
inclusively (i.e., it may be the minimum or maximum, and any value between).
|
||||
|
||||
```php
|
||||
$validator = new Zend\Validator\IsCountable([
|
||||
'min' => 3,
|
||||
'max' => 5,
|
||||
]);
|
||||
|
||||
$validator->isValid([1, 2, 3]); // true; countable, and count is 3
|
||||
$validator->isValid(new ArrayObject([1, 2, 3])); // true; countable, and count is 3
|
||||
$validator->isValid(range(1, 5)); // true; countable, and count is 5
|
||||
$validator->isValid(new ArrayObject(range(1, 5))); // true; countable, and count is 5
|
||||
$validator->isValid([1, 2]); // false; countable, and count is 2
|
||||
$validator->isValid(new ArrayObject([1, 2])); // false; countable, and count is 2
|
||||
$validator->isValid(range(1, 6)); // false; countable, and count is 6
|
||||
$validator->isValid(new ArrayObject(range(1, 6))); // false; countable, and count is 6
|
||||
```
|
@@ -1,86 +0,0 @@
|
||||
# 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)
|
@@ -1,43 +0,0 @@
|
||||
# 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
|
||||
}
|
||||
```
|
@@ -1,48 +0,0 @@
|
||||
# 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`.
|
@@ -1,80 +0,0 @@
|
||||
# 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.
|
@@ -1,41 +0,0 @@
|
||||
# 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
|
||||
```
|
@@ -1,70 +0,0 @@
|
||||
# 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
|
||||
```
|
@@ -1,41 +0,0 @@
|
||||
# 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
|
||||
```
|
@@ -1,127 +0,0 @@
|
||||
# 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.
|
||||
- `length`: Holds the actual length of the 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.
|
||||
|
||||
## Validation Messages
|
||||
Using the setMessage() method you can set another message to be returned in case of the specified failure.
|
||||
|
||||
```php
|
||||
$validator = new Zend\Validator\StringLength(['min' => 3, 'max' => 30]);
|
||||
$validator->setMessage('Youre string is too long. You typed '%length%' chars.', Zend\Validator\StringLength::TOO_LONG);
|
||||
```
|
@@ -1,37 +0,0 @@
|
||||
# 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
|
||||
```
|
@@ -1,30 +0,0 @@
|
||||
# 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
|
||||
}
|
||||
```
|
@@ -1,38 +0,0 @@
|
||||
# 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
|
||||
}
|
||||
```
|
@@ -1,222 +0,0 @@
|
||||
# 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 boundary 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()`.
|
64
vendor/zendframework/zend-validator/mkdocs.yml
vendored
64
vendor/zendframework/zend-validator/mkdocs.yml
vendored
@@ -1,64 +0,0 @@
|
||||
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
|
||||
- Explode: validators/explode.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
|
||||
- IsCountable: validators/is-countable.md
|
||||
- IsInstanceOf: validators/isinstanceof.md
|
||||
- LessThan: validators/less-than.md
|
||||
- NotEmpty: validators/not-empty.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>'
|
@@ -1,8 +0,0 @@
|
||||
<?xml version="1.0"?>
|
||||
<ruleset name="Zend Framework coding standard">
|
||||
<rule ref="./vendor/zendframework/zend-coding-standard/ruleset.xml"/>
|
||||
|
||||
<!-- Paths to check -->
|
||||
<file>src</file>
|
||||
<file>test</file>
|
||||
</ruleset>
|
@@ -133,9 +133,9 @@ abstract class AbstractValidator implements
|
||||
foreach ($options as $name => $option) {
|
||||
$fname = 'set' . ucfirst($name);
|
||||
$fname2 = 'is' . ucfirst($name);
|
||||
if (($name != 'setOptions') && method_exists($this, $name)) {
|
||||
if (($name !== 'setOptions') && method_exists($this, $name)) {
|
||||
$this->{$name}($option);
|
||||
} elseif (($fname != 'setOptions') && method_exists($this, $fname)) {
|
||||
} elseif (($fname !== 'setOptions') && method_exists($this, $fname)) {
|
||||
$this->{$fname}($option);
|
||||
} elseif (method_exists($this, $fname2)) {
|
||||
$this->{$fname2}($option);
|
||||
|
@@ -279,7 +279,7 @@ class CreditCard extends AbstractValidator
|
||||
$foundl = false;
|
||||
foreach ($types as $type) {
|
||||
foreach ($this->cardType[$type] as $prefix) {
|
||||
if (substr($value, 0, strlen($prefix)) == $prefix) {
|
||||
if (0 === strpos($value, $prefix)) {
|
||||
$foundp = true;
|
||||
if (in_array($length, $this->cardLength[$type])) {
|
||||
$foundl = true;
|
||||
|
26
vendor/zendframework/zend-validator/src/Date.php
vendored
26
vendor/zendframework/zend-validator/src/Date.php
vendored
@@ -3,7 +3,7 @@
|
||||
* 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)
|
||||
* @copyright Copyright (c) 2005-2019 Zend Technologies USA Inc. (http://www.zend.com)
|
||||
* @license http://framework.zend.com/license/new-bsd New BSD License
|
||||
*/
|
||||
|
||||
@@ -56,6 +56,11 @@ class Date extends AbstractValidator
|
||||
*/
|
||||
protected $format = self::FORMAT_DEFAULT;
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
protected $strict = false;
|
||||
|
||||
/**
|
||||
* Sets validator options
|
||||
*
|
||||
@@ -100,6 +105,17 @@ class Date extends AbstractValidator
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function setStrict(bool $strict) : self
|
||||
{
|
||||
$this->strict = $strict;
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function isStrict() : bool
|
||||
{
|
||||
return $this->strict;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if $value is a DateTime instance or can be converted into one.
|
||||
*
|
||||
@@ -110,11 +126,17 @@ class Date extends AbstractValidator
|
||||
{
|
||||
$this->setValue($value);
|
||||
|
||||
if (! $this->convertToDateTime($value)) {
|
||||
$date = $this->convertToDateTime($value);
|
||||
if (! $date) {
|
||||
$this->error(self::INVALID_DATE);
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->isStrict() && $date->format($this->getFormat()) !== $value) {
|
||||
$this->error(self::FALSEFORMAT);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
@@ -166,10 +166,10 @@ class DateStep extends Date
|
||||
if (strpos($this->format, 'Y-\WW') === 0
|
||||
&& preg_match('/^([0-9]{4})\-W([0-9]{2})/', $value, $matches)
|
||||
) {
|
||||
$date = new DateTime;
|
||||
$date = new DateTime();
|
||||
$date->setISODate($matches[1], $matches[2]);
|
||||
} else {
|
||||
$date = DateTime::createFromFormat($this->format, $value, $this->timezone);
|
||||
$date = DateTime::createFromFormat($this->format, $value, new DateTimeZone('UTC'));
|
||||
}
|
||||
|
||||
// Invalid dates can show up as warnings (ie. "2007-02-99")
|
||||
|
0
vendor/zendframework/zend-validator/src/Db/AbstractDb.php
vendored
Normal file → Executable file
0
vendor/zendframework/zend-validator/src/Db/AbstractDb.php
vendored
Normal file → Executable file
@@ -206,6 +206,6 @@ class Explode extends AbstractValidator implements ValidatorPluginManagerAwareIn
|
||||
}
|
||||
}
|
||||
|
||||
return count($this->abstractOptions['messages']) == 0;
|
||||
return ! $this->abstractOptions['messages'];
|
||||
}
|
||||
}
|
||||
|
@@ -9,13 +9,15 @@
|
||||
|
||||
namespace Zend\Validator\File;
|
||||
|
||||
use Zend\Validator\Exception;
|
||||
use Zend\Validator\File\FileInformationTrait;
|
||||
|
||||
/**
|
||||
* Validator for the crc32 hash of given files
|
||||
*/
|
||||
class Crc32 extends Hash
|
||||
{
|
||||
use FileInformationTrait;
|
||||
|
||||
/**
|
||||
* @const string Error constants
|
||||
*/
|
||||
@@ -85,32 +87,18 @@ class Crc32 extends Hash
|
||||
*/
|
||||
public function isValid($value, $file = null)
|
||||
{
|
||||
if (is_string($value) && is_array($file)) {
|
||||
// Legacy Zend\Transfer API support
|
||||
$filename = $file['name'];
|
||||
$file = $file['tmp_name'];
|
||||
} elseif (is_array($value)) {
|
||||
if (! isset($value['tmp_name']) || ! isset($value['name'])) {
|
||||
throw new Exception\InvalidArgumentException(
|
||||
'Value array must be in $_FILES format'
|
||||
);
|
||||
}
|
||||
$file = $value['tmp_name'];
|
||||
$filename = $value['name'];
|
||||
} else {
|
||||
$file = $value;
|
||||
$filename = basename($file);
|
||||
}
|
||||
$this->setValue($filename);
|
||||
$fileInfo = $this->getFileInfo($value, $file);
|
||||
|
||||
$this->setValue($fileInfo['filename']);
|
||||
|
||||
// Is file readable ?
|
||||
if (empty($file) || false === is_readable($file)) {
|
||||
if (empty($fileInfo['file']) || false === is_readable($fileInfo['file'])) {
|
||||
$this->error(self::NOT_FOUND);
|
||||
return false;
|
||||
}
|
||||
|
||||
$hashes = array_unique(array_keys($this->getHash()));
|
||||
$filehash = hash_file('crc32', $file);
|
||||
$filehash = hash_file('crc32', $fileInfo['file']);
|
||||
if ($filehash === false) {
|
||||
$this->error(self::NOT_DETECTED);
|
||||
return false;
|
||||
|
@@ -9,6 +9,7 @@
|
||||
|
||||
namespace Zend\Validator\File;
|
||||
|
||||
use Zend\Validator\File\FileInformationTrait;
|
||||
use Zend\Validator\Exception;
|
||||
|
||||
/**
|
||||
@@ -16,6 +17,8 @@ use Zend\Validator\Exception;
|
||||
*/
|
||||
class ExcludeExtension extends Extension
|
||||
{
|
||||
use FileInformationTrait;
|
||||
|
||||
/**
|
||||
* @const string Error constants
|
||||
*/
|
||||
@@ -40,31 +43,21 @@ class ExcludeExtension extends Extension
|
||||
*/
|
||||
public function isValid($value, $file = null)
|
||||
{
|
||||
if (is_string($value) && is_array($file)) {
|
||||
// Legacy Zend\Transfer API support
|
||||
$filename = $file['name'];
|
||||
$file = $file['tmp_name'];
|
||||
} elseif (is_array($value)) {
|
||||
if (! isset($value['tmp_name']) || ! isset($value['name'])) {
|
||||
throw new Exception\InvalidArgumentException(
|
||||
'Value array must be in $_FILES format'
|
||||
);
|
||||
}
|
||||
$file = $value['tmp_name'];
|
||||
$filename = $value['name'];
|
||||
} else {
|
||||
$file = $value;
|
||||
$filename = basename($file);
|
||||
}
|
||||
$this->setValue($filename);
|
||||
$fileInfo = $this->getFileInfo($value, $file);
|
||||
|
||||
// Is file readable ?
|
||||
if (empty($file) || false === is_readable($file)) {
|
||||
if (! $this->getAllowNonExistentFile()
|
||||
&& (empty($fileInfo['file']) || false === is_readable($fileInfo['file']))
|
||||
) {
|
||||
if (preg_match('/nofile\.mo$/', $fileInfo['file'])) {
|
||||
}
|
||||
$this->error(self::NOT_FOUND);
|
||||
return false;
|
||||
}
|
||||
|
||||
$extension = substr($filename, strrpos($filename, '.') + 1);
|
||||
$this->setValue($fileInfo['filename']);
|
||||
|
||||
$extension = substr($fileInfo['filename'], strrpos($fileInfo['filename'], '.') + 1);
|
||||
$extensions = $this->getExtension();
|
||||
|
||||
if ($this->getCase() && (! in_array($extension, $extensions))) {
|
||||
@@ -72,6 +65,8 @@ class ExcludeExtension extends Extension
|
||||
} elseif (! $this->getCase()) {
|
||||
foreach ($extensions as $ext) {
|
||||
if (strtolower($ext) == strtolower($extension)) {
|
||||
if (preg_match('/nofile\.mo$/', $fileInfo['file'])) {
|
||||
}
|
||||
$this->error(self::FALSE_EXTENSION);
|
||||
return false;
|
||||
}
|
||||
|
@@ -10,13 +10,15 @@
|
||||
namespace Zend\Validator\File;
|
||||
|
||||
use finfo;
|
||||
use Zend\Validator\Exception;
|
||||
use Zend\Validator\File\FileInformationTrait;
|
||||
|
||||
/**
|
||||
* Validator for the mime type of a file
|
||||
*/
|
||||
class ExcludeMimeType extends MimeType
|
||||
{
|
||||
use FileInformationTrait;
|
||||
|
||||
const FALSE_TYPE = 'fileExcludeMimeTypeFalse';
|
||||
const NOT_DETECTED = 'fileExcludeMimeTypeNotDetected';
|
||||
const NOT_READABLE = 'fileExcludeMimeTypeNotReadable';
|
||||
@@ -41,29 +43,12 @@ class ExcludeMimeType extends MimeType
|
||||
*/
|
||||
public function isValid($value, $file = null)
|
||||
{
|
||||
if (is_string($value) && is_array($file)) {
|
||||
// Legacy Zend\Transfer API support
|
||||
$filename = $file['name'];
|
||||
$filetype = $file['type'];
|
||||
$file = $file['tmp_name'];
|
||||
} elseif (is_array($value)) {
|
||||
if (! isset($value['tmp_name']) || ! isset($value['name']) || ! isset($value['type'])) {
|
||||
throw new Exception\InvalidArgumentException(
|
||||
'Value array must be in $_FILES format'
|
||||
);
|
||||
}
|
||||
$file = $value['tmp_name'];
|
||||
$filename = $value['name'];
|
||||
$filetype = $value['type'];
|
||||
} else {
|
||||
$file = $value;
|
||||
$filename = basename($file);
|
||||
$filetype = null;
|
||||
}
|
||||
$this->setValue($filename);
|
||||
$fileInfo = $this->getFileInfo($value, $file, true);
|
||||
|
||||
$this->setValue($fileInfo['filename']);
|
||||
|
||||
// Is file readable ?
|
||||
if (empty($file) || false === is_readable($file)) {
|
||||
if (empty($fileInfo['file']) || false === is_readable($fileInfo['file'])) {
|
||||
$this->error(self::NOT_READABLE);
|
||||
return false;
|
||||
}
|
||||
@@ -80,12 +65,12 @@ class ExcludeMimeType extends MimeType
|
||||
|
||||
$this->type = null;
|
||||
if (! empty($this->finfo)) {
|
||||
$this->type = finfo_file($this->finfo, $file);
|
||||
$this->type = finfo_file($this->finfo, $fileInfo['file']);
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($this->type) && $this->getHeaderCheck()) {
|
||||
$this->type = $filetype;
|
||||
$this->type = $fileInfo['filetype'];
|
||||
}
|
||||
|
||||
if (empty($this->type)) {
|
||||
|
@@ -11,12 +11,15 @@ namespace Zend\Validator\File;
|
||||
|
||||
use Zend\Validator\AbstractValidator;
|
||||
use Zend\Validator\Exception;
|
||||
use Zend\Validator\File\FileInformationTrait;
|
||||
|
||||
/**
|
||||
* Validator which checks if the file already exists in the directory
|
||||
*/
|
||||
class Exists extends AbstractValidator
|
||||
{
|
||||
use FileInformationTrait;
|
||||
|
||||
/**
|
||||
* @const string Error constants
|
||||
*/
|
||||
@@ -144,31 +147,15 @@ class Exists extends AbstractValidator
|
||||
*/
|
||||
public function isValid($value, $file = null)
|
||||
{
|
||||
if (is_string($value) && is_array($file)) {
|
||||
// Legacy Zend\Transfer API support
|
||||
$filename = $file['name'];
|
||||
$file = $file['tmp_name'];
|
||||
$this->setValue($filename);
|
||||
} elseif (is_array($value)) {
|
||||
if (! isset($value['tmp_name']) || ! isset($value['name'])) {
|
||||
throw new Exception\InvalidArgumentException(
|
||||
'Value array must be in $_FILES format'
|
||||
);
|
||||
}
|
||||
$file = $value['tmp_name'];
|
||||
$filename = basename($file);
|
||||
$this->setValue($value['name']);
|
||||
} else {
|
||||
$file = $value;
|
||||
$filename = basename($file);
|
||||
$this->setValue($filename);
|
||||
}
|
||||
$fileInfo = $this->getFileInfo($value, $file, false, true);
|
||||
|
||||
$this->setValue($fileInfo['filename']);
|
||||
|
||||
$check = false;
|
||||
$directories = $this->getDirectory(true);
|
||||
if (! isset($directories)) {
|
||||
$check = true;
|
||||
if (! file_exists($file)) {
|
||||
if (! file_exists($fileInfo['file'])) {
|
||||
$this->error(self::DOES_NOT_EXIST);
|
||||
return false;
|
||||
}
|
||||
@@ -179,7 +166,7 @@ class Exists extends AbstractValidator
|
||||
}
|
||||
|
||||
$check = true;
|
||||
if (! file_exists($directory . DIRECTORY_SEPARATOR . $filename)) {
|
||||
if (! file_exists($directory . DIRECTORY_SEPARATOR . $fileInfo['basename'])) {
|
||||
$this->error(self::DOES_NOT_EXIST);
|
||||
return false;
|
||||
}
|
||||
|
@@ -12,6 +12,7 @@ namespace Zend\Validator\File;
|
||||
use Traversable;
|
||||
use Zend\Stdlib\ArrayUtils;
|
||||
use Zend\Validator\AbstractValidator;
|
||||
use Zend\Validator\File\FileInformationTrait;
|
||||
use Zend\Validator\Exception;
|
||||
|
||||
/**
|
||||
@@ -19,6 +20,8 @@ use Zend\Validator\Exception;
|
||||
*/
|
||||
class Extension extends AbstractValidator
|
||||
{
|
||||
use FileInformationTrait;
|
||||
|
||||
/**
|
||||
* @const string Error constants
|
||||
*/
|
||||
@@ -41,6 +44,7 @@ class Extension extends AbstractValidator
|
||||
protected $options = [
|
||||
'case' => false, // Validate case sensitive
|
||||
'extension' => '', // List of extensions
|
||||
'allowNonExistentFile' => false, // Allow validation even if file does not exist
|
||||
];
|
||||
|
||||
/**
|
||||
@@ -167,6 +171,28 @@ class Extension extends AbstractValidator
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns whether or not to allow validation of non-existent files.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function getAllowNonExistentFile()
|
||||
{
|
||||
return $this->options['allowNonExistentFile'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the flag indicating whether or not to allow validation of non-existent files.
|
||||
*
|
||||
* @param bool $flag Whether or not to allow validation of non-existent files.
|
||||
* @return self Provides a fluent interface
|
||||
*/
|
||||
public function setAllowNonExistentFile($flag)
|
||||
{
|
||||
$this->options['allowNonExistentFile'] = (bool) $flag;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if and only if the file extension of $value is included in the
|
||||
* set extension list
|
||||
@@ -177,31 +203,19 @@ class Extension extends AbstractValidator
|
||||
*/
|
||||
public function isValid($value, $file = null)
|
||||
{
|
||||
if (is_string($value) && is_array($file)) {
|
||||
// Legacy Zend\Transfer API support
|
||||
$filename = $file['name'];
|
||||
$file = $file['tmp_name'];
|
||||
} elseif (is_array($value)) {
|
||||
if (! isset($value['tmp_name']) || ! isset($value['name'])) {
|
||||
throw new Exception\InvalidArgumentException(
|
||||
'Value array must be in $_FILES format'
|
||||
);
|
||||
}
|
||||
$file = $value['tmp_name'];
|
||||
$filename = $value['name'];
|
||||
} else {
|
||||
$file = $value;
|
||||
$filename = basename($file);
|
||||
}
|
||||
$this->setValue($filename);
|
||||
$fileInfo = $this->getFileInfo($value, $file);
|
||||
|
||||
// Is file readable ?
|
||||
if (empty($file) || false === is_readable($file)) {
|
||||
if (! $this->getAllowNonExistentFile()
|
||||
&& (empty($fileInfo['file']) || false === is_readable($fileInfo['file']))
|
||||
) {
|
||||
$this->error(self::NOT_FOUND);
|
||||
return false;
|
||||
}
|
||||
|
||||
$extension = substr($filename, strrpos($filename, '.') + 1);
|
||||
$this->setValue($fileInfo['filename']);
|
||||
|
||||
$extension = substr($fileInfo['filename'], strrpos($fileInfo['filename'], '.') + 1);
|
||||
$extensions = $this->getExtension();
|
||||
|
||||
if ($this->getCase() && (in_array($extension, $extensions))) {
|
||||
|
166
vendor/zendframework/zend-validator/src/File/FileInformationTrait.php
vendored
Normal file
166
vendor/zendframework/zend-validator/src/File/FileInformationTrait.php
vendored
Normal file
@@ -0,0 +1,166 @@
|
||||
<?php
|
||||
/**
|
||||
* @see https://github.com/zendframework/zend-validator for the canonical source repository
|
||||
* @copyright Copyright (c) 2019 Zend Technologies USA Inc. (https://www.zend.com)
|
||||
* @license https://github.com/zendframework/zend-validator/blob/master/LICENSE.md New BSD License
|
||||
*/
|
||||
|
||||
namespace Zend\Validator\File;
|
||||
|
||||
use Psr\Http\Message\UploadedFileInterface;
|
||||
use Zend\Validator\Exception;
|
||||
|
||||
trait FileInformationTrait
|
||||
{
|
||||
/**
|
||||
* Returns array if the procedure is identified
|
||||
*
|
||||
* @param string|array|object $value Filename to check
|
||||
* @param null|array $file File data (when using legacy Zend_File_Transfer API)
|
||||
* @param bool $hasType Return with filetype (optional)
|
||||
* @param bool $basename Return with basename - is calculated from location path (optional)
|
||||
* @return array
|
||||
*/
|
||||
protected function getFileInfo(
|
||||
$value,
|
||||
array $file = null,
|
||||
$hasType = false,
|
||||
$hasBasename = false
|
||||
) {
|
||||
if (is_string($value) && is_array($file)) {
|
||||
return $this->getLegacyFileInfo($file, $hasType, $hasBasename);
|
||||
}
|
||||
|
||||
if (is_array($value)) {
|
||||
return $this->getSapiFileInfo($value, $hasType, $hasBasename);
|
||||
}
|
||||
|
||||
if ($value instanceof UploadedFileInterface) {
|
||||
return $this->getPsr7FileInfo($value, $hasType, $hasBasename);
|
||||
}
|
||||
|
||||
return $this->getFileBasedFileInfo($value, $hasType, $hasBasename);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate file information array with legacy Zend_File_Transfer API
|
||||
*
|
||||
* @param array $file File data
|
||||
* @param bool $hasType Return with filetype
|
||||
* @param bool $hasBasename Basename is calculated from location path
|
||||
* @return array
|
||||
*/
|
||||
private function getLegacyFileInfo(
|
||||
array $file,
|
||||
$hasType = false,
|
||||
$hasBasename = false
|
||||
) {
|
||||
$fileInfo = [];
|
||||
|
||||
$fileInfo['filename'] = $file['name'];
|
||||
$fileInfo['file'] = $file['tmp_name'];
|
||||
|
||||
if ($hasBasename) {
|
||||
$fileInfo['basename'] = basename($fileInfo['file']);
|
||||
}
|
||||
|
||||
if ($hasType) {
|
||||
$fileInfo['filetype'] = $file['type'];
|
||||
}
|
||||
|
||||
return $fileInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate file information array with SAPI
|
||||
*
|
||||
* @param array $file File data from SAPI
|
||||
* @param bool $hasType Return with filetype
|
||||
* @param bool $hasBasename Filename is calculated from location path
|
||||
* @return array
|
||||
*/
|
||||
private function getSapiFileInfo(
|
||||
array $file,
|
||||
$hasType = false,
|
||||
$hasBasename = false
|
||||
) {
|
||||
if (! isset($file['tmp_name']) || ! isset($file['name'])) {
|
||||
throw new Exception\InvalidArgumentException(
|
||||
'Value array must be in $_FILES format'
|
||||
);
|
||||
}
|
||||
|
||||
$fileInfo = [];
|
||||
|
||||
$fileInfo['file'] = $file['tmp_name'];
|
||||
$fileInfo['filename'] = $file['name'];
|
||||
|
||||
if ($hasBasename) {
|
||||
$fileInfo['basename'] = basename($fileInfo['file']);
|
||||
}
|
||||
|
||||
if ($hasType) {
|
||||
$fileInfo['filetype'] = $file['type'];
|
||||
}
|
||||
|
||||
return $fileInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate file information array with PSR-7 UploadedFileInterface
|
||||
*
|
||||
* @param UploadedFileInterface $file
|
||||
* @param bool $hasType Return with filetype
|
||||
* @param bool $hasBasename Filename is calculated from location path
|
||||
* @return array
|
||||
*/
|
||||
private function getPsr7FileInfo(
|
||||
UploadedFileInterface $file,
|
||||
$hasType = false,
|
||||
$hasBasename = false
|
||||
) {
|
||||
$fileInfo = [];
|
||||
|
||||
$fileInfo['file'] = $file->getStream()->getMetadata('uri');
|
||||
$fileInfo['filename'] = $file->getClientFilename();
|
||||
|
||||
if ($hasBasename) {
|
||||
$fileInfo['basename'] = basename($fileInfo['file']);
|
||||
}
|
||||
|
||||
if ($hasType) {
|
||||
$fileInfo['filetype'] = $file->getClientMediaType();
|
||||
}
|
||||
|
||||
return $fileInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate file information array with base method
|
||||
*
|
||||
* @param string $file File path
|
||||
* @param bool $hasType Return with filetype
|
||||
* @param bool $hasBasename Filename is calculated from location path
|
||||
* @return array
|
||||
*/
|
||||
private function getFileBasedFileInfo(
|
||||
$file,
|
||||
$hasType = false,
|
||||
$hasBasename = false
|
||||
) {
|
||||
$fileInfo = [];
|
||||
|
||||
$fileInfo['file'] = $file;
|
||||
$fileInfo['filename'] = basename($fileInfo['file']);
|
||||
|
||||
if ($hasBasename) {
|
||||
$fileInfo['basename'] = basename($fileInfo['file']);
|
||||
}
|
||||
|
||||
if ($hasType) {
|
||||
$fileInfo['filetype'] = null;
|
||||
}
|
||||
|
||||
return $fileInfo;
|
||||
}
|
||||
}
|
@@ -151,7 +151,7 @@ class FilesSize extends Size
|
||||
}
|
||||
}
|
||||
|
||||
if (count($this->getMessages()) > 0) {
|
||||
if ($this->getMessages()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
@@ -11,12 +11,15 @@ namespace Zend\Validator\File;
|
||||
|
||||
use Zend\Validator\AbstractValidator;
|
||||
use Zend\Validator\Exception;
|
||||
use Zend\Validator\File\FileInformationTrait;
|
||||
|
||||
/**
|
||||
* Validator for the hash of given files
|
||||
*/
|
||||
class Hash extends AbstractValidator
|
||||
{
|
||||
use FileInformationTrait;
|
||||
|
||||
/**
|
||||
* @const string Error constants
|
||||
*/
|
||||
@@ -114,6 +117,12 @@ class Hash extends AbstractValidator
|
||||
}
|
||||
|
||||
foreach ($options as $value) {
|
||||
if (! is_string($value)) {
|
||||
throw new Exception\InvalidArgumentException(sprintf(
|
||||
'Hash must be a string, %s received',
|
||||
is_object($value) ? get_class($value) : gettype($value)
|
||||
));
|
||||
}
|
||||
$this->options['hash'][$value] = $algorithm;
|
||||
}
|
||||
|
||||
@@ -129,43 +138,27 @@ class Hash extends AbstractValidator
|
||||
*/
|
||||
public function isValid($value, $file = null)
|
||||
{
|
||||
if (is_string($value) && is_array($file)) {
|
||||
// Legacy Zend\Transfer API support
|
||||
$filename = $file['name'];
|
||||
$file = $file['tmp_name'];
|
||||
} elseif (is_array($value)) {
|
||||
if (! isset($value['tmp_name']) || ! isset($value['name'])) {
|
||||
throw new Exception\InvalidArgumentException(
|
||||
'Value array must be in $_FILES format'
|
||||
);
|
||||
}
|
||||
$file = $value['tmp_name'];
|
||||
$filename = $value['name'];
|
||||
} else {
|
||||
$file = $value;
|
||||
$filename = basename($file);
|
||||
}
|
||||
$this->setValue($filename);
|
||||
$fileInfo = $this->getFileInfo($value, $file);
|
||||
|
||||
$this->setValue($fileInfo['filename']);
|
||||
|
||||
// Is file readable ?
|
||||
if (empty($file) || false === is_readable($file)) {
|
||||
if (empty($fileInfo['file']) || false === is_readable($fileInfo['file'])) {
|
||||
$this->error(self::NOT_FOUND);
|
||||
return false;
|
||||
}
|
||||
|
||||
$algos = array_unique(array_values($this->getHash()));
|
||||
$hashes = array_unique(array_keys($this->getHash()));
|
||||
$algos = array_unique(array_values($this->getHash()));
|
||||
foreach ($algos as $algorithm) {
|
||||
$filehash = hash_file($algorithm, $file);
|
||||
$filehash = hash_file($algorithm, $fileInfo['file']);
|
||||
|
||||
if ($filehash === false) {
|
||||
$this->error(self::NOT_DETECTED);
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach ($hashes as $hash) {
|
||||
if ($filehash === $hash) {
|
||||
return true;
|
||||
}
|
||||
if (isset($this->getHash()[$filehash]) && $this->getHash()[$filehash] === $algorithm) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -12,12 +12,15 @@ namespace Zend\Validator\File;
|
||||
use Zend\Stdlib\ErrorHandler;
|
||||
use Zend\Validator\AbstractValidator;
|
||||
use Zend\Validator\Exception;
|
||||
use Zend\Validator\File\FileInformationTrait;
|
||||
|
||||
/**
|
||||
* Validator for the image size of an image file
|
||||
*/
|
||||
class ImageSize extends AbstractValidator
|
||||
{
|
||||
use FileInformationTrait;
|
||||
|
||||
/**
|
||||
* @const string Error constants
|
||||
*/
|
||||
@@ -332,32 +335,18 @@ class ImageSize extends AbstractValidator
|
||||
*/
|
||||
public function isValid($value, $file = null)
|
||||
{
|
||||
if (is_string($value) && is_array($file)) {
|
||||
// Legacy Zend\Transfer API support
|
||||
$filename = $file['name'];
|
||||
$file = $file['tmp_name'];
|
||||
} elseif (is_array($value)) {
|
||||
if (! isset($value['tmp_name']) || ! isset($value['name'])) {
|
||||
throw new Exception\InvalidArgumentException(
|
||||
'Value array must be in $_FILES format'
|
||||
);
|
||||
}
|
||||
$file = $value['tmp_name'];
|
||||
$filename = $value['name'];
|
||||
} else {
|
||||
$file = $value;
|
||||
$filename = basename($file);
|
||||
}
|
||||
$this->setValue($filename);
|
||||
$fileInfo = $this->getFileInfo($value, $file);
|
||||
|
||||
$this->setValue($fileInfo['filename']);
|
||||
|
||||
// Is file readable ?
|
||||
if (empty($file) || false === is_readable($file)) {
|
||||
if (empty($fileInfo['file']) || false === is_readable($fileInfo['file'])) {
|
||||
$this->error(self::NOT_READABLE);
|
||||
return false;
|
||||
}
|
||||
|
||||
ErrorHandler::start();
|
||||
$size = getimagesize($file);
|
||||
$size = getimagesize($fileInfo['file']);
|
||||
ErrorHandler::stop();
|
||||
|
||||
if (empty($size) || ($size[0] === 0) || ($size[1] === 0)) {
|
||||
@@ -383,7 +372,7 @@ class ImageSize extends AbstractValidator
|
||||
$this->error(self::HEIGHT_TOO_BIG);
|
||||
}
|
||||
|
||||
if (count($this->getMessages()) > 0) {
|
||||
if ($this->getMessages()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
@@ -74,6 +74,7 @@ class IsImage extends MimeType
|
||||
'image/vnd.djvu',
|
||||
'image/vnd.fpx',
|
||||
'image/vnd.net-fpx',
|
||||
'image/webp',
|
||||
'image/x-cmu-raster',
|
||||
'image/x-cmx',
|
||||
'image/x-coreldraw',
|
||||
|
@@ -9,13 +9,15 @@
|
||||
|
||||
namespace Zend\Validator\File;
|
||||
|
||||
use Zend\Validator\Exception;
|
||||
use Zend\Validator\File\FileInformationTrait;
|
||||
|
||||
/**
|
||||
* Validator for the md5 hash of given files
|
||||
*/
|
||||
class Md5 extends Hash
|
||||
{
|
||||
use FileInformationTrait;
|
||||
|
||||
/**
|
||||
* @const string Error constants
|
||||
*/
|
||||
@@ -85,32 +87,18 @@ class Md5 extends Hash
|
||||
*/
|
||||
public function isValid($value, $file = null)
|
||||
{
|
||||
if (is_string($value) && is_array($file)) {
|
||||
// Legacy Zend\Transfer API support
|
||||
$filename = $file['name'];
|
||||
$file = $file['tmp_name'];
|
||||
} elseif (is_array($value)) {
|
||||
if (! isset($value['tmp_name']) || ! isset($value['name'])) {
|
||||
throw new Exception\InvalidArgumentException(
|
||||
'Value array must be in $_FILES format'
|
||||
);
|
||||
}
|
||||
$file = $value['tmp_name'];
|
||||
$filename = $value['name'];
|
||||
} else {
|
||||
$file = $value;
|
||||
$filename = basename($file);
|
||||
}
|
||||
$this->setValue($filename);
|
||||
$fileInfo = $this->getFileInfo($value, $file);
|
||||
|
||||
$this->setValue($fileInfo['filename']);
|
||||
|
||||
// Is file readable ?
|
||||
if (empty($file) || false === is_readable($file)) {
|
||||
if (empty($fileInfo['file']) || false === is_readable($fileInfo['file'])) {
|
||||
$this->error(self::NOT_FOUND);
|
||||
return false;
|
||||
}
|
||||
|
||||
$hashes = array_unique(array_keys($this->getHash()));
|
||||
$filehash = hash_file('md5', $file);
|
||||
$filehash = hash_file('md5', $fileInfo['file']);
|
||||
if ($filehash === false) {
|
||||
$this->error(self::NOT_DETECTED);
|
||||
return false;
|
||||
|
@@ -14,12 +14,15 @@ use Zend\Stdlib\ArrayUtils;
|
||||
use Zend\Stdlib\ErrorHandler;
|
||||
use Zend\Validator\AbstractValidator;
|
||||
use Zend\Validator\Exception;
|
||||
use Zend\Validator\File\FileInformationTrait;
|
||||
|
||||
/**
|
||||
* Validator for the mime type of a file
|
||||
*/
|
||||
class MimeType extends AbstractValidator
|
||||
{
|
||||
use FileInformationTrait;
|
||||
|
||||
/**#@+
|
||||
* @const Error type constants
|
||||
*/
|
||||
@@ -341,29 +344,12 @@ class MimeType extends AbstractValidator
|
||||
*/
|
||||
public function isValid($value, $file = null)
|
||||
{
|
||||
if (is_string($value) && is_array($file)) {
|
||||
// Legacy Zend\Transfer API support
|
||||
$filename = $file['name'];
|
||||
$filetype = $file['type'];
|
||||
$file = $file['tmp_name'];
|
||||
} elseif (is_array($value)) {
|
||||
if (! isset($value['tmp_name']) || ! isset($value['name']) || ! isset($value['type'])) {
|
||||
throw new Exception\InvalidArgumentException(
|
||||
'Value array must be in $_FILES format'
|
||||
);
|
||||
}
|
||||
$file = $value['tmp_name'];
|
||||
$filename = $value['name'];
|
||||
$filetype = $value['type'];
|
||||
} else {
|
||||
$file = $value;
|
||||
$filename = basename($file);
|
||||
$filetype = null;
|
||||
}
|
||||
$this->setValue($filename);
|
||||
$fileInfo = $this->getFileInfo($value, $file, true);
|
||||
|
||||
$this->setValue($fileInfo['filename']);
|
||||
|
||||
// Is file readable ?
|
||||
if (empty($file) || false === is_readable($file)) {
|
||||
if (empty($fileInfo['file']) || false === is_readable($fileInfo['file'])) {
|
||||
$this->error(static::NOT_READABLE);
|
||||
return false;
|
||||
}
|
||||
@@ -384,13 +370,13 @@ class MimeType extends AbstractValidator
|
||||
|
||||
$this->type = null;
|
||||
if (! empty($this->finfo)) {
|
||||
$this->type = finfo_file($this->finfo, $file);
|
||||
$this->type = finfo_file($this->finfo, $fileInfo['file']);
|
||||
unset($this->finfo);
|
||||
}
|
||||
}
|
||||
|
||||
if (empty($this->type) && $this->getHeaderCheck()) {
|
||||
$this->type = $filetype;
|
||||
$this->type = $fileInfo['filetype'];
|
||||
}
|
||||
|
||||
if (empty($this->type)) {
|
||||
|
@@ -10,12 +10,15 @@
|
||||
namespace Zend\Validator\File;
|
||||
|
||||
use Zend\Validator\Exception;
|
||||
use Zend\Validator\File\FileInformationTrait;
|
||||
|
||||
/**
|
||||
* Validator which checks if the destination file does not exist
|
||||
*/
|
||||
class NotExists extends Exists
|
||||
{
|
||||
use FileInformationTrait;
|
||||
|
||||
/**
|
||||
* @const string Error constants
|
||||
*/
|
||||
@@ -37,31 +40,15 @@ class NotExists extends Exists
|
||||
*/
|
||||
public function isValid($value, $file = null)
|
||||
{
|
||||
if (is_string($value) && is_array($file)) {
|
||||
// Legacy Zend\Transfer API support
|
||||
$filename = $file['name'];
|
||||
$file = $file['tmp_name'];
|
||||
$this->setValue($filename);
|
||||
} elseif (is_array($value)) {
|
||||
if (! isset($value['tmp_name']) || ! isset($value['name'])) {
|
||||
throw new Exception\InvalidArgumentException(
|
||||
'Value array must be in $_FILES format'
|
||||
);
|
||||
}
|
||||
$file = $value['tmp_name'];
|
||||
$filename = basename($file);
|
||||
$this->setValue($value['name']);
|
||||
} else {
|
||||
$file = $value;
|
||||
$filename = basename($file);
|
||||
$this->setValue($filename);
|
||||
}
|
||||
$fileInfo = $this->getFileInfo($value, $file, false, true);
|
||||
|
||||
$this->setValue($fileInfo['filename']);
|
||||
|
||||
$check = false;
|
||||
$directories = $this->getDirectory(true);
|
||||
if (! isset($directories)) {
|
||||
$check = true;
|
||||
if (file_exists($file)) {
|
||||
if (file_exists($fileInfo['file'])) {
|
||||
$this->error(self::DOES_EXIST);
|
||||
return false;
|
||||
}
|
||||
@@ -72,7 +59,7 @@ class NotExists extends Exists
|
||||
}
|
||||
|
||||
$check = true;
|
||||
if (file_exists($directory . DIRECTORY_SEPARATOR . $filename)) {
|
||||
if (file_exists($directory . DIRECTORY_SEPARATOR . $fileInfo['basename'])) {
|
||||
$this->error(self::DOES_EXIST);
|
||||
return false;
|
||||
}
|
||||
|
@@ -9,13 +9,15 @@
|
||||
|
||||
namespace Zend\Validator\File;
|
||||
|
||||
use Zend\Validator\Exception;
|
||||
use Zend\Validator\File\FileInformationTrait;
|
||||
|
||||
/**
|
||||
* Validator for the sha1 hash of given files
|
||||
*/
|
||||
class Sha1 extends Hash
|
||||
{
|
||||
use FileInformationTrait;
|
||||
|
||||
/**
|
||||
* @const string Error constants
|
||||
*/
|
||||
@@ -85,32 +87,18 @@ class Sha1 extends Hash
|
||||
*/
|
||||
public function isValid($value, $file = null)
|
||||
{
|
||||
if (is_string($value) && is_array($file)) {
|
||||
// Legacy Zend\Transfer API support
|
||||
$filename = $file['name'];
|
||||
$file = $file['tmp_name'];
|
||||
} elseif (is_array($value)) {
|
||||
if (! isset($value['tmp_name']) || ! isset($value['name'])) {
|
||||
throw new Exception\InvalidArgumentException(
|
||||
'Value array must be in $_FILES format'
|
||||
);
|
||||
}
|
||||
$file = $value['tmp_name'];
|
||||
$filename = $value['name'];
|
||||
} else {
|
||||
$file = $value;
|
||||
$filename = basename($file);
|
||||
}
|
||||
$this->setValue($filename);
|
||||
$fileInfo = $this->getFileInfo($value, $file);
|
||||
|
||||
$this->setValue($fileInfo['filename']);
|
||||
|
||||
// Is file readable ?
|
||||
if (empty($file) || false === is_readable($file)) {
|
||||
if (empty($fileInfo['file']) || false === is_readable($fileInfo['file'])) {
|
||||
$this->error(self::NOT_FOUND);
|
||||
return false;
|
||||
}
|
||||
|
||||
$hashes = array_unique(array_keys($this->getHash()));
|
||||
$filehash = hash_file('sha1', $file);
|
||||
$filehash = hash_file('sha1', $fileInfo['file']);
|
||||
if ($filehash === false) {
|
||||
$this->error(self::NOT_DETECTED);
|
||||
return false;
|
||||
|
@@ -12,12 +12,15 @@ namespace Zend\Validator\File;
|
||||
use Zend\Stdlib\ErrorHandler;
|
||||
use Zend\Validator\AbstractValidator;
|
||||
use Zend\Validator\Exception;
|
||||
use Zend\Validator\File\FileInformationTrait;
|
||||
|
||||
/**
|
||||
* Validator for the maximum size of a file up to a max of 2GB
|
||||
*/
|
||||
class Size extends AbstractValidator
|
||||
{
|
||||
use FileInformationTrait;
|
||||
|
||||
/**
|
||||
* @const string Error constants
|
||||
*/
|
||||
@@ -234,33 +237,19 @@ class Size extends AbstractValidator
|
||||
*/
|
||||
public function isValid($value, $file = null)
|
||||
{
|
||||
if (is_string($value) && is_array($file)) {
|
||||
// Legacy Zend\Transfer API support
|
||||
$filename = $file['name'];
|
||||
$file = $file['tmp_name'];
|
||||
} elseif (is_array($value)) {
|
||||
if (! isset($value['tmp_name']) || ! isset($value['name'])) {
|
||||
throw new Exception\InvalidArgumentException(
|
||||
'Value array must be in $_FILES format'
|
||||
);
|
||||
}
|
||||
$file = $value['tmp_name'];
|
||||
$filename = $value['name'];
|
||||
} else {
|
||||
$file = $value;
|
||||
$filename = basename($file);
|
||||
}
|
||||
$this->setValue($filename);
|
||||
$fileInfo = $this->getFileInfo($value, $file);
|
||||
|
||||
$this->setValue($fileInfo['filename']);
|
||||
|
||||
// Is file readable ?
|
||||
if (empty($file) || false === is_readable($file)) {
|
||||
if (empty($fileInfo['file']) || false === is_readable($fileInfo['file'])) {
|
||||
$this->error(self::NOT_FOUND);
|
||||
return false;
|
||||
}
|
||||
|
||||
// limited to 4GB files
|
||||
ErrorHandler::start();
|
||||
$size = sprintf("%u", filesize($file));
|
||||
$size = sprintf("%u", filesize($fileInfo['file']));
|
||||
ErrorHandler::stop();
|
||||
$this->size = $size;
|
||||
|
||||
@@ -292,7 +281,7 @@ class Size extends AbstractValidator
|
||||
}
|
||||
}
|
||||
|
||||
if (count($this->getMessages()) > 0) {
|
||||
if ($this->getMessages()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
@@ -10,6 +10,7 @@
|
||||
namespace Zend\Validator\File;
|
||||
|
||||
use Countable;
|
||||
use Psr\Http\Message\UploadedFileInterface;
|
||||
use Zend\Validator\AbstractValidator;
|
||||
use Zend\Validator\Exception;
|
||||
|
||||
@@ -37,13 +38,14 @@ class Upload extends AbstractValidator
|
||||
* @var array Error message templates
|
||||
*/
|
||||
protected $messageTemplates = [
|
||||
self::INI_SIZE => "File '%value%' exceeds the defined ini size",
|
||||
self::FORM_SIZE => "File '%value%' exceeds the defined form size",
|
||||
self::INI_SIZE => "File '%value%' exceeds upload_max_filesize directive in php.ini",
|
||||
self::FORM_SIZE => "File '%value%' exceeds the MAX_FILE_SIZE directive that was "
|
||||
. 'specified in the HTML form',
|
||||
self::PARTIAL => "File '%value%' was only partially uploaded",
|
||||
self::NO_FILE => "File '%value%' was not uploaded",
|
||||
self::NO_TMP_DIR => "No temporary directory was found for file '%value%'",
|
||||
self::CANT_WRITE => "File '%value%' can't be written",
|
||||
self::EXTENSION => "A PHP extension returned an error while uploading the file '%value%'",
|
||||
self::NO_TMP_DIR => "Missing a temporary folder to store '%value%'",
|
||||
self::CANT_WRITE => "Failed to write file '%value%' to disk",
|
||||
self::EXTENSION => "A PHP extension stopped uploading the file '%value%'",
|
||||
self::ATTACK => "File '%value%' was illegally uploaded. This could be a possible attack",
|
||||
self::FILE_NOT_FOUND => "File '%value%' was not found",
|
||||
self::UNKNOWN => "Unknown error while uploading file '%value%'"
|
||||
@@ -87,12 +89,16 @@ class Upload extends AbstractValidator
|
||||
$return[$file] = $this->options['files'][$name];
|
||||
}
|
||||
|
||||
if ($content['name'] === $file) {
|
||||
if ($content instanceof UploadedFileInterface) {
|
||||
if ($content->getClientFilename() === $file) {
|
||||
$return[$name] = $this->options['files'][$name];
|
||||
}
|
||||
} elseif ($content['name'] === $file) {
|
||||
$return[$name] = $this->options['files'][$name];
|
||||
}
|
||||
}
|
||||
|
||||
if (count($return) === 0) {
|
||||
if (! $return) {
|
||||
throw new Exception\InvalidArgumentException("The file '$file' was not found");
|
||||
}
|
||||
|
||||
@@ -124,7 +130,9 @@ class Upload extends AbstractValidator
|
||||
}
|
||||
|
||||
foreach ($this->options['files'] as $file => $content) {
|
||||
if (! isset($content['error'])) {
|
||||
if (! $content instanceof UploadedFileInterface
|
||||
&& ! isset($content['error'])
|
||||
) {
|
||||
unset($this->options['files'][$file]);
|
||||
}
|
||||
}
|
||||
@@ -148,6 +156,18 @@ class Upload extends AbstractValidator
|
||||
$files = array_merge($files, $this->getFiles($value));
|
||||
} else {
|
||||
foreach ($this->getFiles() as $file => $content) {
|
||||
if ($content instanceof UploadedFileInterface) {
|
||||
if ($content->getClientFilename() === $value) {
|
||||
$files = array_merge($files, $this->getFiles($file));
|
||||
}
|
||||
|
||||
// PSR cannot search by tmp_name because it does not have
|
||||
// a public interface to get it, only user defined name
|
||||
// from form field.
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
if (isset($content['name']) && ($content['name'] === $value)) {
|
||||
$files = array_merge($files, $this->getFiles($file));
|
||||
}
|
||||
@@ -164,8 +184,19 @@ class Upload extends AbstractValidator
|
||||
|
||||
foreach ($files as $file => $content) {
|
||||
$this->value = $file;
|
||||
switch ($content['error']) {
|
||||
$error = $content instanceof UploadedFileInterface
|
||||
? $content->getError()
|
||||
: $content['error'];
|
||||
|
||||
switch ($error) {
|
||||
case 0:
|
||||
if ($content instanceof UploadedFileInterface) {
|
||||
// done!
|
||||
break;
|
||||
}
|
||||
|
||||
// For standard SAPI environments, check that the upload
|
||||
// was valid
|
||||
if (! is_uploaded_file($content['tmp_name'])) {
|
||||
$this->throwError($content, self::ATTACK);
|
||||
}
|
||||
@@ -205,7 +236,7 @@ class Upload extends AbstractValidator
|
||||
}
|
||||
}
|
||||
|
||||
if (count($this->getMessages()) > 0) {
|
||||
if ($this->getMessages()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -215,7 +246,7 @@ class Upload extends AbstractValidator
|
||||
/**
|
||||
* Throws an error of the given type
|
||||
*
|
||||
* @param string $file
|
||||
* @param array|string|UploadedFileInterface $file
|
||||
* @param string $errorType
|
||||
* @return false
|
||||
*/
|
||||
@@ -228,6 +259,8 @@ class Upload extends AbstractValidator
|
||||
}
|
||||
} elseif (is_string($file)) {
|
||||
$this->value = $file;
|
||||
} elseif ($file instanceof UploadedFileInterface) {
|
||||
$this->value = $file->getClientFilename();
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -9,6 +9,7 @@
|
||||
|
||||
namespace Zend\Validator\File;
|
||||
|
||||
use Psr\Http\Message\UploadedFileInterface;
|
||||
use Zend\Validator\AbstractValidator;
|
||||
use Zend\Validator\Exception;
|
||||
|
||||
@@ -35,22 +36,23 @@ class UploadFile extends AbstractValidator
|
||||
* @var array Error message templates
|
||||
*/
|
||||
protected $messageTemplates = [
|
||||
self::INI_SIZE => "File exceeds the defined ini size",
|
||||
self::FORM_SIZE => "File exceeds the defined form size",
|
||||
self::PARTIAL => "File was only partially uploaded",
|
||||
self::NO_FILE => "File was not uploaded",
|
||||
self::NO_TMP_DIR => "No temporary directory was found for file",
|
||||
self::CANT_WRITE => "File can't be written",
|
||||
self::EXTENSION => "A PHP extension returned an error while uploading the file",
|
||||
self::ATTACK => "File was illegally uploaded. This could be a possible attack",
|
||||
self::FILE_NOT_FOUND => "File was not found",
|
||||
self::UNKNOWN => "Unknown error while uploading file",
|
||||
self::INI_SIZE => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
|
||||
self::FORM_SIZE => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was '
|
||||
. 'specified in the HTML form',
|
||||
self::PARTIAL => 'The uploaded file was only partially uploaded',
|
||||
self::NO_FILE => 'No file was uploaded',
|
||||
self::NO_TMP_DIR => 'Missing a temporary folder',
|
||||
self::CANT_WRITE => 'Failed to write file to disk',
|
||||
self::EXTENSION => 'A PHP extension stopped the file upload',
|
||||
self::ATTACK => 'File was illegally uploaded. This could be a possible attack',
|
||||
self::FILE_NOT_FOUND => 'File was not found',
|
||||
self::UNKNOWN => 'Unknown error while uploading file',
|
||||
];
|
||||
|
||||
/**
|
||||
* Returns true if and only if the file was uploaded without errors
|
||||
*
|
||||
* @param string $value File to check for upload errors
|
||||
* @param string|array|UploadedFileInterface $value File to check for upload errors
|
||||
* @return bool
|
||||
* @throws Exception\InvalidArgumentException
|
||||
*/
|
||||
@@ -62,62 +64,106 @@ class UploadFile extends AbstractValidator
|
||||
'Value array must be in $_FILES format'
|
||||
);
|
||||
}
|
||||
$file = $value['tmp_name'];
|
||||
$filename = $value['name'];
|
||||
$error = $value['error'];
|
||||
} else {
|
||||
$file = $value;
|
||||
$filename = basename($file);
|
||||
$error = 0;
|
||||
}
|
||||
$this->setValue($filename);
|
||||
|
||||
return $this->validateUploadedFile(
|
||||
$value['error'],
|
||||
$value['name'],
|
||||
$value['tmp_name']
|
||||
);
|
||||
}
|
||||
|
||||
if ($value instanceof UploadedFileInterface) {
|
||||
return $this->validatePsr7UploadedFile($value);
|
||||
}
|
||||
|
||||
if (is_string($value)) {
|
||||
return $this->validateUploadedFile(0, basename($value), $value);
|
||||
}
|
||||
|
||||
$this->error(self::UNKNOWN);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $error UPLOAD_ERR_* constant value
|
||||
* @return bool
|
||||
*/
|
||||
private function validateFileFromErrorCode($error)
|
||||
{
|
||||
switch ($error) {
|
||||
case UPLOAD_ERR_OK:
|
||||
if (empty($file) || false === is_file($file)) {
|
||||
$this->error(self::FILE_NOT_FOUND);
|
||||
} elseif (! is_uploaded_file($file)) {
|
||||
$this->error(self::ATTACK);
|
||||
}
|
||||
break;
|
||||
return true;
|
||||
|
||||
case UPLOAD_ERR_INI_SIZE:
|
||||
$this->error(self::INI_SIZE);
|
||||
break;
|
||||
return false;
|
||||
|
||||
case UPLOAD_ERR_FORM_SIZE:
|
||||
$this->error(self::FORM_SIZE);
|
||||
break;
|
||||
return false;
|
||||
|
||||
case UPLOAD_ERR_PARTIAL:
|
||||
$this->error(self::PARTIAL);
|
||||
break;
|
||||
return false;
|
||||
|
||||
case UPLOAD_ERR_NO_FILE:
|
||||
$this->error(self::NO_FILE);
|
||||
break;
|
||||
return false;
|
||||
|
||||
case UPLOAD_ERR_NO_TMP_DIR:
|
||||
$this->error(self::NO_TMP_DIR);
|
||||
break;
|
||||
return false;
|
||||
|
||||
case UPLOAD_ERR_CANT_WRITE:
|
||||
$this->error(self::CANT_WRITE);
|
||||
break;
|
||||
return false;
|
||||
|
||||
case UPLOAD_ERR_EXTENSION:
|
||||
$this->error(self::EXTENSION);
|
||||
break;
|
||||
return false;
|
||||
|
||||
default:
|
||||
$this->error(self::UNKNOWN);
|
||||
break;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $error UPLOAD_ERR_* constant
|
||||
* @param string $filename
|
||||
* @param string $uploadedFile Name of uploaded file (gen tmp_name)
|
||||
* @return bool
|
||||
*/
|
||||
private function validateUploadedFile($error, $filename, $uploadedFile)
|
||||
{
|
||||
$this->setValue($filename);
|
||||
|
||||
// Normal errors can be validated normally
|
||||
if ($error !== UPLOAD_ERR_OK) {
|
||||
return $this->validateFileFromErrorCode($error);
|
||||
}
|
||||
|
||||
if (count($this->getMessages()) > 0) {
|
||||
// Did we get no name? Is the file missing?
|
||||
if (empty($uploadedFile) || false === is_file($uploadedFile)) {
|
||||
$this->error(self::FILE_NOT_FOUND);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Do we have an invalid upload?
|
||||
if (! is_uploaded_file($uploadedFile)) {
|
||||
$this->error(self::ATTACK);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
private function validatePsr7UploadedFile(UploadedFileInterface $uploadedFile)
|
||||
{
|
||||
$this->setValue($uploadedFile);
|
||||
return $this->validateFileFromErrorCode($uploadedFile->getError());
|
||||
}
|
||||
}
|
||||
|
@@ -11,12 +11,15 @@ namespace Zend\Validator\File;
|
||||
|
||||
use Zend\Validator\AbstractValidator;
|
||||
use Zend\Validator\Exception;
|
||||
use Zend\Validator\File\FileInformationTrait;
|
||||
|
||||
/**
|
||||
* Validator for counting all words in a file
|
||||
*/
|
||||
class WordCount extends AbstractValidator
|
||||
{
|
||||
use FileInformationTrait;
|
||||
|
||||
/**
|
||||
* @const string Error constants
|
||||
*/
|
||||
@@ -175,31 +178,17 @@ class WordCount extends AbstractValidator
|
||||
*/
|
||||
public function isValid($value, $file = null)
|
||||
{
|
||||
if (is_string($value) && is_array($file)) {
|
||||
// Legacy Zend\Transfer API support
|
||||
$filename = $file['name'];
|
||||
$file = $file['tmp_name'];
|
||||
} elseif (is_array($value)) {
|
||||
if (! isset($value['tmp_name']) || ! isset($value['name'])) {
|
||||
throw new Exception\InvalidArgumentException(
|
||||
'Value array must be in $_FILES format'
|
||||
);
|
||||
}
|
||||
$file = $value['tmp_name'];
|
||||
$filename = $value['name'];
|
||||
} else {
|
||||
$file = $value;
|
||||
$filename = basename($file);
|
||||
}
|
||||
$this->setValue($filename);
|
||||
$fileInfo = $this->getFileInfo($value, $file);
|
||||
|
||||
$this->setValue($fileInfo['filename']);
|
||||
|
||||
// Is file readable ?
|
||||
if (empty($file) || false === is_readable($file)) {
|
||||
if (empty($fileInfo['file']) || false === is_readable($fileInfo['file'])) {
|
||||
$this->error(self::NOT_FOUND);
|
||||
return false;
|
||||
}
|
||||
|
||||
$content = file_get_contents($file);
|
||||
$content = file_get_contents($fileInfo['file']);
|
||||
$this->count = str_word_count($content);
|
||||
if (($this->getMax() !== null) && ($this->count > $this->getMax())) {
|
||||
$this->error(self::TOO_MUCH);
|
||||
|
@@ -69,7 +69,7 @@ class Hostname extends AbstractValidator
|
||||
|
||||
/**
|
||||
* Array of valid top-level-domains
|
||||
* IanaVersion 2018013101
|
||||
* IanaVersion 2019122700
|
||||
*
|
||||
* @see ftp://data.iana.org/TLD/tlds-alpha-by-domain.txt List of all TLDs by domain
|
||||
* @see http://www.iana.org/domains/root/db/ Official list of supported TLDs
|
||||
@@ -92,7 +92,6 @@ class Hostname extends AbstractValidator
|
||||
'accountant',
|
||||
'accountants',
|
||||
'aco',
|
||||
'active',
|
||||
'actor',
|
||||
'ad',
|
||||
'adac',
|
||||
@@ -222,7 +221,6 @@ class Hostname extends AbstractValidator
|
||||
'bj',
|
||||
'black',
|
||||
'blackfriday',
|
||||
'blanco',
|
||||
'blockbuster',
|
||||
'blog',
|
||||
'bloomberg',
|
||||
@@ -231,7 +229,6 @@ class Hostname extends AbstractValidator
|
||||
'bms',
|
||||
'bmw',
|
||||
'bn',
|
||||
'bnl',
|
||||
'bnpparibas',
|
||||
'bo',
|
||||
'boats',
|
||||
@@ -242,7 +239,6 @@ class Hostname extends AbstractValidator
|
||||
'boo',
|
||||
'book',
|
||||
'booking',
|
||||
'boots',
|
||||
'bosch',
|
||||
'bostik',
|
||||
'boston',
|
||||
@@ -291,7 +287,6 @@ class Hostname extends AbstractValidator
|
||||
'career',
|
||||
'careers',
|
||||
'cars',
|
||||
'cartier',
|
||||
'casa',
|
||||
'case',
|
||||
'caseih',
|
||||
@@ -317,13 +312,13 @@ class Hostname extends AbstractValidator
|
||||
'ch',
|
||||
'chanel',
|
||||
'channel',
|
||||
'charity',
|
||||
'chase',
|
||||
'chat',
|
||||
'cheap',
|
||||
'chintai',
|
||||
'christmas',
|
||||
'chrome',
|
||||
'chrysler',
|
||||
'church',
|
||||
'ci',
|
||||
'cipriani',
|
||||
@@ -375,6 +370,7 @@ class Hostname extends AbstractValidator
|
||||
'coupon',
|
||||
'coupons',
|
||||
'courses',
|
||||
'cpa',
|
||||
'cr',
|
||||
'credit',
|
||||
'creditcard',
|
||||
@@ -436,9 +432,7 @@ class Hostname extends AbstractValidator
|
||||
'do',
|
||||
'docs',
|
||||
'doctor',
|
||||
'dodge',
|
||||
'dog',
|
||||
'doha',
|
||||
'domains',
|
||||
'dot',
|
||||
'download',
|
||||
@@ -447,7 +441,6 @@ class Hostname extends AbstractValidator
|
||||
'dubai',
|
||||
'duck',
|
||||
'dunlop',
|
||||
'duns',
|
||||
'dupont',
|
||||
'durban',
|
||||
'dvag',
|
||||
@@ -468,7 +461,6 @@ class Hostname extends AbstractValidator
|
||||
'engineer',
|
||||
'engineering',
|
||||
'enterprises',
|
||||
'epost',
|
||||
'epson',
|
||||
'equipment',
|
||||
'er',
|
||||
@@ -484,7 +476,6 @@ class Hostname extends AbstractValidator
|
||||
'eurovision',
|
||||
'eus',
|
||||
'events',
|
||||
'everbank',
|
||||
'exchange',
|
||||
'expert',
|
||||
'exposed',
|
||||
@@ -564,6 +555,7 @@ class Hostname extends AbstractValidator
|
||||
'games',
|
||||
'gap',
|
||||
'garden',
|
||||
'gay',
|
||||
'gb',
|
||||
'gbiz',
|
||||
'gd',
|
||||
@@ -599,7 +591,6 @@ class Hostname extends AbstractValidator
|
||||
'goldpoint',
|
||||
'golf',
|
||||
'goo',
|
||||
'goodhands',
|
||||
'goodyear',
|
||||
'goog',
|
||||
'google',
|
||||
@@ -657,7 +648,6 @@ class Hostname extends AbstractValidator
|
||||
'homes',
|
||||
'homesense',
|
||||
'honda',
|
||||
'honeywell',
|
||||
'horse',
|
||||
'hospital',
|
||||
'host',
|
||||
@@ -691,6 +681,7 @@ class Hostname extends AbstractValidator
|
||||
'immo',
|
||||
'immobilien',
|
||||
'in',
|
||||
'inc',
|
||||
'industries',
|
||||
'infiniti',
|
||||
'info',
|
||||
@@ -710,7 +701,6 @@ class Hostname extends AbstractValidator
|
||||
'ir',
|
||||
'irish',
|
||||
'is',
|
||||
'iselect',
|
||||
'ismaili',
|
||||
'ist',
|
||||
'istanbul',
|
||||
@@ -718,7 +708,6 @@ class Hostname extends AbstractValidator
|
||||
'itau',
|
||||
'itv',
|
||||
'iveco',
|
||||
'iwc',
|
||||
'jaguar',
|
||||
'java',
|
||||
'jcb',
|
||||
@@ -728,7 +717,6 @@ class Hostname extends AbstractValidator
|
||||
'jetzt',
|
||||
'jewelry',
|
||||
'jio',
|
||||
'jlc',
|
||||
'jll',
|
||||
'jm',
|
||||
'jmp',
|
||||
@@ -777,12 +765,10 @@ class Hostname extends AbstractValidator
|
||||
'kz',
|
||||
'la',
|
||||
'lacaixa',
|
||||
'ladbrokes',
|
||||
'lamborghini',
|
||||
'lamer',
|
||||
'lancaster',
|
||||
'lancia',
|
||||
'lancome',
|
||||
'land',
|
||||
'landrover',
|
||||
'lanxess',
|
||||
@@ -821,6 +807,8 @@ class Hostname extends AbstractValidator
|
||||
'living',
|
||||
'lixil',
|
||||
'lk',
|
||||
'llc',
|
||||
'llp',
|
||||
'loan',
|
||||
'loans',
|
||||
'locker',
|
||||
@@ -875,7 +863,6 @@ class Hostname extends AbstractValidator
|
||||
'memorial',
|
||||
'men',
|
||||
'menu',
|
||||
'meo',
|
||||
'merckmsd',
|
||||
'metlife',
|
||||
'mg',
|
||||
@@ -897,7 +884,6 @@ class Hostname extends AbstractValidator
|
||||
'mo',
|
||||
'mobi',
|
||||
'mobile',
|
||||
'mobily',
|
||||
'moda',
|
||||
'moe',
|
||||
'moi',
|
||||
@@ -905,7 +891,6 @@ class Hostname extends AbstractValidator
|
||||
'monash',
|
||||
'money',
|
||||
'monster',
|
||||
'mopar',
|
||||
'mormon',
|
||||
'mortgage',
|
||||
'moscow',
|
||||
@@ -913,7 +898,6 @@ class Hostname extends AbstractValidator
|
||||
'motorcycles',
|
||||
'mov',
|
||||
'movie',
|
||||
'movistar',
|
||||
'mp',
|
||||
'mq',
|
||||
'mr',
|
||||
@@ -1011,7 +995,6 @@ class Hostname extends AbstractValidator
|
||||
'pa',
|
||||
'page',
|
||||
'panasonic',
|
||||
'panerai',
|
||||
'paris',
|
||||
'pars',
|
||||
'partners',
|
||||
@@ -1034,7 +1017,6 @@ class Hostname extends AbstractValidator
|
||||
'photography',
|
||||
'photos',
|
||||
'physio',
|
||||
'piaget',
|
||||
'pics',
|
||||
'pictet',
|
||||
'pictures',
|
||||
@@ -1150,7 +1132,6 @@ class Hostname extends AbstractValidator
|
||||
'sandvikcoromant',
|
||||
'sanofi',
|
||||
'sap',
|
||||
'sapo',
|
||||
'sarl',
|
||||
'sas',
|
||||
'save',
|
||||
@@ -1232,21 +1213,18 @@ class Hostname extends AbstractValidator
|
||||
'sony',
|
||||
'soy',
|
||||
'space',
|
||||
'spiegel',
|
||||
'sport',
|
||||
'spot',
|
||||
'spreadbetting',
|
||||
'sr',
|
||||
'srl',
|
||||
'srt',
|
||||
'ss',
|
||||
'st',
|
||||
'stada',
|
||||
'staples',
|
||||
'star',
|
||||
'starhub',
|
||||
'statebank',
|
||||
'statefarm',
|
||||
'statoil',
|
||||
'stc',
|
||||
'stcgroup',
|
||||
'stockholm',
|
||||
@@ -1292,8 +1270,6 @@ class Hostname extends AbstractValidator
|
||||
'tech',
|
||||
'technology',
|
||||
'tel',
|
||||
'telecity',
|
||||
'telefonica',
|
||||
'temasek',
|
||||
'tennis',
|
||||
'teva',
|
||||
@@ -1353,7 +1329,6 @@ class Hostname extends AbstractValidator
|
||||
'ua',
|
||||
'ubank',
|
||||
'ubs',
|
||||
'uconnect',
|
||||
'ug',
|
||||
'uk',
|
||||
'unicom',
|
||||
@@ -1387,7 +1362,6 @@ class Hostname extends AbstractValidator
|
||||
'virgin',
|
||||
'visa',
|
||||
'vision',
|
||||
'vista',
|
||||
'vistaprint',
|
||||
'viva',
|
||||
'vivo',
|
||||
@@ -1407,7 +1381,6 @@ class Hostname extends AbstractValidator
|
||||
'walter',
|
||||
'wang',
|
||||
'wanggou',
|
||||
'warman',
|
||||
'watch',
|
||||
'watches',
|
||||
'weather',
|
||||
@@ -1535,9 +1508,9 @@ class Hostname extends AbstractValidator
|
||||
'اتصالات',
|
||||
'امارات',
|
||||
'بازار',
|
||||
'موريتانيا',
|
||||
'پاکستان',
|
||||
'الاردن',
|
||||
'موبايلي',
|
||||
'بارت',
|
||||
'بھارت',
|
||||
'المغرب',
|
||||
@@ -1569,6 +1542,7 @@ class Hostname extends AbstractValidator
|
||||
'大拿',
|
||||
'みんな',
|
||||
'グーグル',
|
||||
'ευ',
|
||||
'ελ',
|
||||
'世界',
|
||||
'書籍',
|
||||
@@ -1594,7 +1568,6 @@ class Hostname extends AbstractValidator
|
||||
'新加坡',
|
||||
'فلسطين',
|
||||
'政务',
|
||||
'xperia',
|
||||
'xxx',
|
||||
'xyz',
|
||||
'yachts',
|
||||
@@ -1614,7 +1587,6 @@ class Hostname extends AbstractValidator
|
||||
'zara',
|
||||
'zero',
|
||||
'zip',
|
||||
'zippo',
|
||||
'zm',
|
||||
'zone',
|
||||
'zuerich',
|
||||
@@ -1636,7 +1608,7 @@ class Hostname extends AbstractValidator
|
||||
* (.CH) Switzerland https://nic.switch.ch/reg/ocView.action?res=EF6GW2JBPVTG67DLNIQXU234MN6SC33JNQQGI7L6#anhang1
|
||||
* (.CL) Chile http://www.iana.org/domains/idn-tables/tables/cl_latn_1.0.html
|
||||
* (.COM) International http://www.verisign.com/information-services/naming-services/internationalized-domain-names/index.html
|
||||
* (.DE) Germany http://www.denic.de/en/domains/idns/liste.html
|
||||
* (.DE) Germany https://www.denic.de/en/know-how/idn-domains/idn-character-list/
|
||||
* (.DK) Danmark http://www.dk-hostmaster.dk/index.php?id=151
|
||||
* (.EE) Estonia https://www.iana.org/domains/idn-tables/tables/pl_et-pl_1.0.html
|
||||
* (.ES) Spain https://www.nic.es/media/2008-05/1210147705287.pdf
|
||||
@@ -1648,7 +1620,7 @@ class Hostname extends AbstractValidator
|
||||
* (.INFO) International http://www.nic.info/info/idn
|
||||
* (.IO) British Indian Ocean Territory http://www.nic.io/IO-IDN-Policy.pdf
|
||||
* (.IR) Iran http://www.nic.ir/Allowable_Characters_dot-iran
|
||||
* (.IS) Iceland http://www.isnic.is/domain/rules.php
|
||||
* (.IS) Iceland https://www.isnic.is/en/domain/rules#2
|
||||
* (.KR) Korea http://www.iana.org/domains/idn-tables/tables/kr_ko-kr_1.0.html
|
||||
* (.LI) Liechtenstein https://nic.switch.ch/reg/ocView.action?res=EF6GW2JBPVTG67DLNIQXU234MN6SC33JNQQGI7L6#anhang1
|
||||
* (.LT) Lithuania http://www.domreg.lt/static/doc/public/idn_symbols-en.pdf
|
||||
@@ -1689,7 +1661,7 @@ class Hostname extends AbstractValidator
|
||||
'CL' => [1 => '/^[\x{002d}0-9a-záéíñóúü]{1,63}$/iu'],
|
||||
'CN' => 'Hostname/Cn.php',
|
||||
'COM' => 'Hostname/Com.php',
|
||||
'DE' => [1 => '/^[\x{002d}0-9a-zà-öø-ÿăąāćĉčċďđĕěėęēğĝġģĥħĭĩįīıĵķĺľļłńňņŋŏőōœĸŕřŗśŝšşťţŧŭůűũųūŵŷźžż]{1,63}$/iu'],
|
||||
'DE' => [1 => '/^[\x{002d}0-9a-záàăâåäãąāæćĉčċçďđéèĕêěëėęēğĝġģĥħíìĭîïĩįīıĵķĺľļłńňñņŋóòŏôöőõøōœĸŕřŗśŝšşßťţŧúùŭûůüűũųūŵýŷÿźžżðþ]{1,63}$/iu'],
|
||||
'DK' => [1 => '/^[\x{002d}0-9a-zäåæéöøü]{1,63}$/iu'],
|
||||
'EE' => [1 => '/^[\x{002d}0-9a-zäõöüšž]{1,63}$/iu'],
|
||||
'ES' => [1 => '/^[\x{002d}0-9a-zàáçèéíïñòóúü·]{1,63}$/iu'],
|
||||
@@ -1769,6 +1741,7 @@ class Hostname extends AbstractValidator
|
||||
33 => '/^[\x{002d}0-9א-ת]{1,63}$/iu'],
|
||||
'PR' => [1 => '/^[\x{002d}0-9a-záéíóúñäëïüöâêîôûàèùæçœãõ]{1,63}$/iu'],
|
||||
'PT' => [1 => '/^[\x{002d}0-9a-záàâãçéêíóôõú]{1,63}$/iu'],
|
||||
'RS' => [1 => '/^[\x{002d}0-9a-zßáâäçéëíîóôöúüýăąćčďđęěĺľłńňőŕřśşšţťůűźżž]{1,63}$/iu'],
|
||||
'RU' => [1 => '/^[\x{002d}0-9а-яё]{1,63}$/iu'],
|
||||
'SA' => [1 => '/^[\x{002d}.0-9\x{0621}-\x{063A}\x{0641}-\x{064A}\x{0660}-\x{0669}]{1,63}$/iu'],
|
||||
'SE' => [1 => '/^[\x{002d}0-9a-zäåéöü]{1,63}$/iu'],
|
||||
@@ -2061,6 +2034,7 @@ class Hostname extends AbstractValidator
|
||||
}
|
||||
|
||||
// Match TLD against known list
|
||||
$removedTld = false;
|
||||
if ($this->getTldCheck()) {
|
||||
if (! in_array(strtolower($this->tld), $this->validTlds)
|
||||
&& ! in_array($this->tld, $this->validTlds)) {
|
||||
@@ -2071,6 +2045,7 @@ class Hostname extends AbstractValidator
|
||||
// We have already validated that the TLD is fine. We don't want it to go through the below
|
||||
// checks as new UTF-8 TLDs will incorrectly fail if there is no IDN regex for it.
|
||||
array_pop($domainParts);
|
||||
$removedTld = true;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -2090,6 +2065,10 @@ class Hostname extends AbstractValidator
|
||||
|
||||
// Check each hostname part
|
||||
$check = 0;
|
||||
$lastDomainPart = end($domainParts);
|
||||
if (! $removedTld) {
|
||||
$lastDomainPart = prev($domainParts);
|
||||
}
|
||||
foreach ($domainParts as $domainPart) {
|
||||
// Decode Punycode domain names to IDN
|
||||
if (strpos($domainPart, 'xn--') === 0) {
|
||||
@@ -2099,6 +2078,13 @@ class Hostname extends AbstractValidator
|
||||
}
|
||||
}
|
||||
|
||||
// Skip following checks if domain part is empty, as it definitely is not a valid hostname then
|
||||
if ($domainPart === '') {
|
||||
$this->error(self::INVALID_HOSTNAME);
|
||||
$status = false;
|
||||
break 2;
|
||||
}
|
||||
|
||||
// Check dash (-) does not start, end or appear in 3rd and 4th positions
|
||||
if ($utf8StrWrapper->strpos($domainPart, '-') === 0
|
||||
|| ($utf8StrWrapper->strlen($domainPart) > 2
|
||||
@@ -2118,7 +2104,9 @@ class Hostname extends AbstractValidator
|
||||
|
||||
// Check each domain part
|
||||
$checked = false;
|
||||
foreach ($regexChars as $regexKey => $regexChar) {
|
||||
$isSubDomain = $domainPart != $lastDomainPart;
|
||||
$partRegexChars = $isSubDomain ? ['/^[a-z0-9_\x2d]{1,63}$/i'] + $regexChars : $regexChars;
|
||||
foreach ($partRegexChars as $regexKey => $regexChar) {
|
||||
$status = preg_match($regexChar, $domainPart);
|
||||
if ($status > 0) {
|
||||
$length = 63;
|
||||
|
2
vendor/zendframework/zend-validator/src/Isbn/Isbn10.php
vendored
Normal file → Executable file
2
vendor/zendframework/zend-validator/src/Isbn/Isbn10.php
vendored
Normal file → Executable file
@@ -32,7 +32,7 @@ class Isbn10
|
||||
$sum = 0;
|
||||
|
||||
for ($i = 0; $i < 9; $i++) {
|
||||
$sum += (10 - $i) * $value{$i};
|
||||
$sum += (10 - $i) * $value[$i];
|
||||
}
|
||||
|
||||
return $sum;
|
||||
|
4
vendor/zendframework/zend-validator/src/Isbn/Isbn13.php
vendored
Normal file → Executable file
4
vendor/zendframework/zend-validator/src/Isbn/Isbn13.php
vendored
Normal file → Executable file
@@ -33,11 +33,11 @@ class Isbn13
|
||||
|
||||
for ($i = 0; $i < 12; $i++) {
|
||||
if ($i % 2 == 0) {
|
||||
$sum += $value{$i};
|
||||
$sum += $value[$i];
|
||||
continue;
|
||||
}
|
||||
|
||||
$sum += 3 * $value{$i};
|
||||
$sum += 3 * $value[$i];
|
||||
}
|
||||
|
||||
return $sum;
|
||||
|
31
vendor/zendframework/zend-validator/src/Step.php
vendored
31
vendor/zendframework/zend-validator/src/Step.php
vendored
@@ -122,7 +122,9 @@ class Step extends AbstractValidator
|
||||
|
||||
$this->setValue($value);
|
||||
|
||||
$fmod = $this->fmod($value - $this->baseValue, $this->step);
|
||||
$substract = $this->sub($value, $this->baseValue);
|
||||
|
||||
$fmod = $this->fmod($substract, $this->step);
|
||||
|
||||
if ($fmod !== 0.0 && $fmod !== $this->step) {
|
||||
$this->error(self::NOT_STEP);
|
||||
@@ -146,10 +148,31 @@ class Step extends AbstractValidator
|
||||
}
|
||||
|
||||
//find the maximum precision from both input params to give accurate results
|
||||
$xFloatSegment = substr($x, strpos($x, '.') + 1) ?: '';
|
||||
$yFloatSegment = substr($y, strpos($y, '.') + 1) ?: '';
|
||||
$precision = strlen($xFloatSegment) + strlen($yFloatSegment);
|
||||
$precision = $this->getPrecision($x) + $this->getPrecision($y);
|
||||
|
||||
return round($x - $y * floor($x / $y), $precision);
|
||||
}
|
||||
|
||||
/**
|
||||
* replaces the internal substraction operation which give wrong results on some cases
|
||||
*
|
||||
* @param float $x
|
||||
* @param float $y
|
||||
* @return float
|
||||
*/
|
||||
private function sub($x, $y)
|
||||
{
|
||||
$precision = $this->getPrecision($x) + $this->getPrecision($y);
|
||||
return round($x - $y, $precision);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param float $float
|
||||
* @return int
|
||||
*/
|
||||
private function getPrecision($float)
|
||||
{
|
||||
$segment = substr($float, strpos($float, '.') + 1);
|
||||
return $segment ? strlen($segment) : 0;
|
||||
}
|
||||
}
|
||||
|
@@ -226,7 +226,7 @@ class StringLength extends AbstractValidator
|
||||
$this->error(self::TOO_LONG);
|
||||
}
|
||||
|
||||
if (count($this->getMessages())) {
|
||||
if ($this->getMessages()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
156
vendor/zendframework/zend-validator/src/UndisclosedPassword.php
vendored
Normal file
156
vendor/zendframework/zend-validator/src/UndisclosedPassword.php
vendored
Normal file
@@ -0,0 +1,156 @@
|
||||
<?php
|
||||
/**
|
||||
* @link http://github.com/zendframework/zend-validator for the canonical source repository
|
||||
* @copyright Copyright (c) 2019 Zend Technologies USA Inc. (https://www.zend.com)
|
||||
* @license http://framework.zend.com/license/new-bsd New BSD License
|
||||
*/
|
||||
|
||||
namespace Zend\Validator;
|
||||
|
||||
use Psr\Http\Client\ClientExceptionInterface;
|
||||
use Psr\Http\Client\ClientInterface;
|
||||
use Psr\Http\Message\RequestFactoryInterface;
|
||||
use Psr\Http\Message\ResponseFactoryInterface;
|
||||
|
||||
final class UndisclosedPassword extends AbstractValidator
|
||||
{
|
||||
private const HIBP_API_URI = 'https://api.pwnedpasswords.com';
|
||||
private const HIBP_API_REQUEST_TIMEOUT = 300;
|
||||
private const HIBP_CLIENT_USER_AGENT_STRING = 'zend-validator';
|
||||
private const HIBP_CLIENT_ACCEPT_HEADER = 'application/vnd.haveibeenpwned.v2+json';
|
||||
private const HIBP_K_ANONYMITY_HASH_RANGE_LENGTH = 5;
|
||||
private const HIBP_K_ANONYMITY_HASH_RANGE_BASE = 0;
|
||||
private const SHA1_STRING_LENGTH = 40;
|
||||
|
||||
private const PASSWORD_BREACHED = 'passwordBreached';
|
||||
private const NOT_A_STRING = 'wrongInput';
|
||||
|
||||
protected $messageTemplates = [
|
||||
self::PASSWORD_BREACHED =>
|
||||
'The provided password was found in previous breaches, please create another password',
|
||||
self::NOT_A_STRING => 'The provided password is not a string, please provide a correct password',
|
||||
];
|
||||
|
||||
/**
|
||||
* @var ClientInterface
|
||||
*/
|
||||
private $httpClient;
|
||||
|
||||
/**
|
||||
* @var RequestFactoryInterface
|
||||
*/
|
||||
private $makeHttpRequest;
|
||||
|
||||
/**
|
||||
* @var ResponseFactoryInterface
|
||||
*/
|
||||
private $makeHttpResponse;
|
||||
|
||||
/**
|
||||
* PasswordBreach constructor.
|
||||
*/
|
||||
public function __construct(
|
||||
ClientInterface $httpClient,
|
||||
RequestFactoryInterface $makeHttpRequest,
|
||||
ResponseFactoryInterface $makeHttpResponse
|
||||
) {
|
||||
$this->httpClient = $httpClient;
|
||||
$this->makeHttpRequest = $makeHttpRequest;
|
||||
$this->makeHttpResponse = $makeHttpResponse;
|
||||
}
|
||||
|
||||
/**
|
||||
* @inheritDoc
|
||||
*/
|
||||
public function isValid($value)
|
||||
{
|
||||
if (! is_string($value)) {
|
||||
$this->error(self::NOT_A_STRING);
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($this->isPwnedPassword($value)) {
|
||||
$this->error(self::PASSWORD_BREACHED);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function isPwnedPassword(string $password) : bool
|
||||
{
|
||||
$sha1Hash = $this->hashPassword($password);
|
||||
$rangeHash = $this->getRangeHash($sha1Hash);
|
||||
$hashList = $this->retrieveHashList($rangeHash);
|
||||
return $this->hashInResponse($sha1Hash, $hashList);
|
||||
}
|
||||
|
||||
/**
|
||||
* We use a SHA1 hashed password for checking it against
|
||||
* the breached data set of HIBP.
|
||||
*
|
||||
* @param string $password
|
||||
* @return string
|
||||
*/
|
||||
private function hashPassword(string $password) : string
|
||||
{
|
||||
$hashedPassword = \sha1($password);
|
||||
return strtoupper($hashedPassword);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a hash range that will be send to HIBP API
|
||||
* applying K-Anonymity
|
||||
*
|
||||
* @param string $passwordHash
|
||||
* @return string
|
||||
* @see https://www.troyhunt.com/enhancing-pwned-passwords-privacy-by-exclusively-supporting-anonymity/
|
||||
*/
|
||||
private function getRangeHash(string $passwordHash) : string
|
||||
{
|
||||
return substr($passwordHash, self::HIBP_K_ANONYMITY_HASH_RANGE_BASE, self::HIBP_K_ANONYMITY_HASH_RANGE_LENGTH);
|
||||
}
|
||||
|
||||
/**
|
||||
* Making a connection to the HIBP API to retrieve a
|
||||
* list of hashes that all have the same range as we
|
||||
* provided.
|
||||
*
|
||||
* @param string $passwordRange
|
||||
* @return string
|
||||
* @throws ClientExceptionInterface
|
||||
*/
|
||||
private function retrieveHashList(string $passwordRange) : string
|
||||
{
|
||||
$request = $this->makeHttpRequest->createRequest(
|
||||
'GET',
|
||||
self::HIBP_API_URI . '/range/' . $passwordRange
|
||||
);
|
||||
|
||||
$response = $this->httpClient->sendRequest($request);
|
||||
return (string) $response->getBody();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the password is in the response from HIBP
|
||||
*
|
||||
* @param string $sha1Hash
|
||||
* @param string $resultStream
|
||||
* @return bool
|
||||
*/
|
||||
private function hashInResponse(string $sha1Hash, string $resultStream) : bool
|
||||
{
|
||||
$data = explode("\r\n", $resultStream);
|
||||
$hashes = array_filter($data, function ($value) use ($sha1Hash) {
|
||||
list($hash, $count) = explode(':', $value);
|
||||
if (0 === strcmp($hash, substr($sha1Hash, self::HIBP_K_ANONYMITY_HASH_RANGE_LENGTH))) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
if ([] === $hashes) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user