## File: README.md

[](https://packagist.org/packages/yiisoft/hydrator-validator)
[](https://packagist.org/packages/yiisoft/hydrator-validator)
[](https://github.com/yiisoft/hydrator-validator/actions/workflows/build.yml)
[](https://codecov.io/gh/yiisoft/hydrator-validator)
[](https://dashboard.stryker-mutator.io/reports/github.com/yiisoft/hydrator-validator/master)
[](https://github.com/yiisoft/hydrator-validator/actions?query=workflow%3A%22static+analysis%22)
[](https://shepherd.dev/github/yiisoft/hydrator-validator)
[](https://shepherd.dev/github/yiisoft/hydrator-validator)

The package provides a [hydrator](https://github.com/yiisoft/hydrator)
that also does [validation](https://github.com/yiisoft/validator), including raw data.
It's useful when input data comes from a user, and you need to validate it and then put it into DTOs.

## Requirements

- PHP 8.0 - 8.5.

## Installation

The package could be installed with [Composer](https://getcomposer.org):

```shell
composer require yiisoft/hydrator-validator
```

## General usage

Validating hydrator is a decorator for [hydrator](https://github.com/yiisoft/hydrator) that allows to validate:

- raw data of properties marked with `Validate` PHP attribute;
- an object after creating or populating it.

To use it, the object being validated must implement `ValidatedInputInterface`. You can use `ValidatedInputTrait` to
easily create such object. The validation rules for raw values of the object are defined with `Validate` PHP attribute.

Example of object:

```php
use Yiisoft\Hydrator\Validator\Attribute\Validate;
use Yiisoft\Hydrator\Validator\ValidatedInputInterface;
use Yiisoft\Hydrator\Validator\ValidatedInputTrait;
use Yiisoft\Validator\Rule\Email;
use Yiisoft\Validator\Rule\Required;

final class InputDto implements ValidatedInputInterface 
{
    use ValidatedInputTrait;
    
    #[Email]
    private string $email;
    
    #[Validate(new Required())]
    private string $name;
}
```

Validation result could be obtained via `getValidationResult()` method. For further working with result, refer to 
corresponding [validator's guide section](https://github.com/yiisoft/validator/blob/master/docs/guide/en/result.md).

Validating hydrator usage example:

```php
use Psr\Http\Message\RequestInterface;
use Yiisoft\Hydrator\Validator\ValidatingHydrator;

public function actionEdit(RequestInterface $request, ValidatingHydrator $hydrator): ResponseInterface
{
    $data = $request->getParsedBody();    
    $inputDto = $hydrator->create(InputDto::class, $data);
    
    if (!$inputDto->getValidationResult()->isValid()) {
        // Validation didn't pass :(
    }
    
    // Everything is fine. You can use $inputDto now.    
}
```

## Documentation

- [Internals](docs/internals.md)

If you need help or have a question, the [Yii Forum](https://forum.yiiframework.com/c/yii-3-0/63) is a good place for that.
You may also check out other [Yii Community Resources](https://www.yiiframework.com/community).

## License

The Yii Validating Hydrator is free software. It is released under the terms of the BSD License.
Please see [`LICENSE`](./LICENSE.md) for more information.

Maintained by [Yii Software](https://www.yiiframework.com/).

## Support the project

[](https://opencollective.com/yiisoft)

## Follow updates

[](https://www.yiiframework.com/)
[](https://twitter.com/yiiframework)
[](https://t.me/yii3en)
[](https://www.facebook.com/groups/yiitalk)
[](https://yiiframework.com/go/slack)

---

## File: CHANGELOG.md

# Yii Validating Hydrator Change Log

## 2.0.3 under development

- no changes in this release.

## 2.0.2 December 16, 2025

- Chg #29, #33: Change PHP constraint in `composer.json` to `8.0 - 8.5` (@vjik)
- Bug #31: Clear the `result` property of the `ValidateResolver` object after hydration (@olegbaturin)

## 2.0.1 August 06, 2024

- Enh #24: Add `yiisoft/validator` of version `^2.0` support (@vjik)

## 2.0.0 March 06, 2024

- Chg #17: Throws `LogicException` on call `ValidatedInputInterface::getValidatedInput()` method when object is not
  validated (@vjik)

## 1.0.0 February 02, 2024

- Initial release.

---

## File: composer.json

{
    "name": "yiisoft/hydrator-validator",
    "type": "library",
    "description": "Validating hydrator with raw data validation support",
    "keywords": [
        "input",
        "validation"
    ],
    "homepage": "https://www.yiiframework.com/",
    "license": "BSD-3-Clause",
    "support": {
        "issues": "https://github.com/yiisoft/hydrator-validator/issues?state=open",
        "source": "https://github.com/yiisoft/hydrator-validator",
        "forum": "https://www.yiiframework.com/forum/",
        "wiki": "https://www.yiiframework.com/wiki/",
        "irc": "ircs://irc.libera.chat:6697/yii",
        "chat": "https://t.me/yii3en"
    },
    "funding": [
        {
            "type": "opencollective",
            "url": "https://opencollective.com/yiisoft"
        },
        {
            "type": "github",
            "url": "https://github.com/sponsors/yiisoft"
        }
    ],
    "require": {
        "php": "8.0 - 8.5",
        "yiisoft/hydrator": "^1.0",
        "yiisoft/validator": "^1.0 || ^2.0"
    },
    "require-dev": {
        "friendsofphp/php-cs-fixer": "^3.66",
        "phpunit/phpunit": "^9.6.22",
        "rector/rector": "^2.0.11",
        "roave/infection-static-analysis-plugin": "^1.25",
        "shipmonk/composer-dependency-analyser": "^1.8",
        "spatie/phpunit-watcher": "^1.23.6",
        "vimeo/psalm": "^4.30 || ^5.26.1 || ^6.9.6",
        "yiisoft/injector": "^1.2",
        "yiisoft/test-support": "^3.0.2"
    },
    "autoload": {
        "psr-4": {
            "Yiisoft\\Hydrator\\Validator\\": "src"
        }
    },
    "autoload-dev": {
        "psr-4": {
            "Yiisoft\\Hydrator\\Validator\\Tests\\": "tests"
        }
    },
    "config": {
        "sort-packages": true,
        "allow-plugins": {
            "infection/extension-installer": true,
            "composer/package-versions-deprecated": true
        }
    },
    "scripts": {
        "dependency-analyser": "composer-dependency-analyser",
        "test": "phpunit --testdox --no-interaction",
        "test-watch": "phpunit-watcher watch"
    }
}

---

## File: LICENSE.md

Copyright © 2008 by Yii Software (<https://www.yiiframework.com/>)
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

 * Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in
   the documentation and/or other materials provided with the
   distribution.
 * Neither the name of Yii Software nor the names of its
   contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

---

## File: UPGRADE.md

# Upgrading Instructions for Yii Validating Hydrator

This file contains the upgrade notes. These notes highlight changes that could break your
application when you upgrade the package from one version to another.

> **Important!** The following upgrading instructions are cumulative. That is, if you want
> to upgrade from version A to version C and there is version B between A and C, you need
> to following the instructions for both A and B.

## Upgrade from 1.x to 2.x

If you use `ValidatedInputInterface::getValidatedInput()` on non-validated inputs or form models, wrap it with
`try ... catch`:

```php
$result = $input->getValidatedInput();
// ↓
try {
    $result = $input->getValidatedInput();
} catch (LogicException) {
    $result = null;
}
```

---

## File: .phpunit-watcher.yml

watch:
  directories:
    - src
    - tests
  fileMask: '*.php'
notifications:
  passingTests: false
  failingTests: false
phpunit:
  binaryPath: vendor/bin/phpunit
  timeout: 180

---

## File: docs/internals.md

# Internals

## Unit testing

The package is tested with [PHPUnit](https://phpunit.de/). To run tests:

```shell
./vendor/bin/phpunit
```

## Mutation testing

The package tests are checked with [Infection](https://infection.github.io/) mutation framework with
[Infection Static Analysis Plugin](https://github.com/Roave/infection-static-analysis-plugin). To run it:

```shell
./vendor/bin/roave-infection-static-analysis-plugin
```

## Static analysis

The code is statically analyzed with [Psalm](https://psalm.dev/). To run static analysis:

```shell
./vendor/bin/psalm
```

## Code style

Use [Rector](https://github.com/rectorphp/rector) to make codebase follow some specific rules or
use either newest or any specific version of PHP:

```shell
./vendor/bin/rector
```

## Dependencies

Use [Composer Dependency Analyser](https://github.com/shipmonk-rnd/composer-dependency-analyser) to detect unknown,
shadow, and unused [Composer](https://getcomposer.org) dependencies:

```shell
./vendor/bin/composer-dependency-analyser
```

---

## File: .github/CODE_OF_CONDUCT.md

# Yii Contributor Code of Conduct

## Our Pledge

As contributors and maintainers of this project, and in order to keep Yii community open and welcoming, we ask to
respect all community members.

## Our Standards

Examples of behavior that contributes to a positive environment for our community include:

* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall community

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery, and sexual attention or advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting

## Enforcement Responsibilities

Core team members are responsible for clarifying and enforcing our standards of acceptable behavior and will take 
appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.

Core team members have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits,
issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for 
moderation decisions when appropriate.

## Scope

This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing
the community in public spaces. Examples of representing a project or community include using an official e-mail
address, posting via an official social media account, within project GitHub, official forum or acting as an appointed
representative at an online or offline event.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting core team members. All
complaints will be reviewed and investigated promptly and fairly.

All core team members are obligated to respect the privacy and security of the reporter of any incident.

## Enforcement Guidelines

Core team members will follow these Community Impact Guidelines in determining the consequences for any action they
deem in violation of this Code of Conduct:

### 1. Correction

**Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in 
the community.

**Consequence**: A private, written warning from core team members, providing clarity around the nature of the violation
and an explanation of why the behavior was inappropriate. A public apology may be requested.

### 2. Warning

**Community Impact**: A violation through a single incident or series of actions.

**Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including
unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding
interactions in community spaces as well as external channels like social media. Violating these terms may lead to 
a temporary or permanent ban.

### 3. Temporary Ban

**Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.

**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified
period of time. No public or private interaction with the people involved, including unsolicited interaction with those
enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.

### 4. Permanent Ban

**Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate
behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.

**Consequence**: A permanent ban from any sort of public interaction within the community.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].

Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC].

For answers to common questions about this code of conduct, see the FAQ at
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
[https://www.contributor-covenant.org/translations][translations].

[homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
[Mozilla CoC]: https://github.com/mozilla/diversity
[FAQ]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations

---

## File: .github/CONTRIBUTING.md

# Prerequisites

- [Yii goal and values](https://github.com/yiisoft/docs/blob/master/001-yii-values.md)
- [Namespaces](https://github.com/yiisoft/docs/blob/master/004-namespaces.md)
- [Git commit messages](https://github.com/yiisoft/docs/blob/master/006-git-commit-messages.md)
- [Exceptions](https://github.com/yiisoft/docs/blob/master/007-exceptions.md)
- [Interfaces](https://github.com/yiisoft/docs/blob/master/008-interfaces.md)

# Getting started

Since Yii 3 consists of many packages, we have a [special development tool](https://github.com/yiisoft/docs/blob/master/005-development-tool.md).

1. [Clone the repository](https://github.com/yiisoft/yii-dev-tool).

2. [Set up your own fork](https://github.com/yiisoft/yii-dev-tool#using-your-own-fork).

3. Now you are ready. Fork any package listed in `packages.php` and do `./yii-dev install username/package`.

If you don't have any particular package in mind to start with:

- [Check roadmap](https://github.com/yiisoft/docs/blob/master/003-roadmap.md).
- Check package issues at github. Usually there are some.
- Ask @samdark.

---

## File: .github/dependabot.yml

version: 2
updates:
  - package-ecosystem: "github-actions"
    directory: "/"
    schedule:
      interval: "weekly"
    cooldown:
      default-days: 7
    groups:
      github-actions:
        patterns: [ "*" ]
    ignore:
      - dependency-name: "yiisoft/*"

  - package-ecosystem: "composer"
    directory: "/"
    schedule:
      interval: "daily"
    cooldown:
      default-days: 7
    groups:
      composer-dev-dependencies:
        dependency-type: "development"
    versioning-strategy: "widen"

---

## File: .github/PULL_REQUEST_TEMPLATE.md

| Q             | A
| ------------- | ---
| Is bugfix?    | ✔️/❌
| New feature?  | ✔️/❌
| Breaks BC?    | ✔️/❌

---

## File: .github/SECURITY.md

# Security Policy

Please use the [security issue form](https://www.yiiframework.com/security) to report to us any security issue you
find in Yii. DO NOT use the issue tracker or discuss it in the public forum as it will cause more damage than help.

Please note that as a non-commercial OpenSource project we are not able to pay bounties at the moment.

---

## File: .github/workflows/bc.yml

name: backwards compatibility

on:
  pull_request:
    paths: &paths
      - 'src/**'
      - 'composer.json'
      - '.github/workflows/bc.yml'
  push:
    branches: ['master']
    paths: *paths

permissions:
  contents: read

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  roave_bc_check:
    uses: yiisoft/actions/.github/workflows/bc.yml@master
    with:
      os: >-
        ['ubuntu-latest']
      php: >-
        ['8.5']

---

## File: .github/workflows/build.yml

name: build

on:
  pull_request:
    paths: &paths
      - 'src/**'
      - 'tests/**'
      - 'phpunit.xml.dist'
      - 'composer.json'
      - '.github/workflows/build.yml'
  push:
    branches: ['master']
    paths: *paths

permissions:
  contents: read

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  phpunit:
    uses: yiisoft/actions/.github/workflows/phpunit.yml@master
    secrets:
      codecovToken: ${{ secrets.CODECOV_TOKEN }}
    with:
      os: >-
        ['ubuntu-latest', 'windows-latest']
      php: >-
        ['8.0', '8.1', '8.2', '8.3', '8.4', '8.5']

---

## File: .github/workflows/changelog.yml

name: changelog

on:
  pull_request:
    paths:
      - 'src/**'

permissions:
  contents: read

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  changelog:
    uses: yiisoft/actions/.github/workflows/changelog.yml@master

---

## File: .github/workflows/composer-dependency-analyser.yml

name: composer dependency analyser

on:
  pull_request:
    paths: &paths
      - 'src/**'
      - 'tests/**'
      - '.github/workflows/composer-dependency-analyser.yml'
      - 'composer.json'
      - 'composer-dependency-analyser.php'
  push:
    branches: ['master']
    paths: *paths

permissions:
  contents: read

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  composer-dependency-analyser:
    uses: yiisoft/actions/.github/workflows/composer-dependency-analyser.yml@master
    with:
      php: >-
        ['8.0', '8.1', '8.2', '8.3', '8.4', '8.5']

---

## File: .github/workflows/mutation.yml

name: mutation test

on:
  pull_request:
    paths: &paths
      - 'src/**'
      - 'tests/**'
      - 'phpunit.xml.dist'
      - 'infection.json.dist'
      - 'composer.json'
      - '.github/workflows/mutation.yml'
  push:
    branches: ['master']
    paths: *paths

permissions:
  contents: read

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  mutation:
    uses: yiisoft/actions/.github/workflows/roave-infection.yml@master
    with:
      min-covered-msi: 100
      os: >-
        ['ubuntu-latest']
      php: >-
        ['8.3']
    secrets:
      STRYKER_DASHBOARD_API_KEY: ${{ secrets.STRYKER_DASHBOARD_API_KEY }}

---

## File: .github/workflows/rector-cs.yml

name: Rector + PHP CS Fixer

on:
  pull_request:
    paths:
      - 'src/**'
      - 'tests/**'
      - '.github/workflows/rector-cs.yml'
      - 'composer.json'
      - 'rector.php'
      - '.php-cs-fixer.dist.php'

permissions:
  contents: read

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  rector:
    permissions:
      contents: write  # Required to commit formatting fixes back to the PR
    uses: yiisoft/actions/.github/workflows/rector-cs.yml@master
    with:
      php: '8.0'

---

## File: .github/workflows/static.yml

name: static analysis

on:
  pull_request:
    paths: &paths
      - 'src/**'
      - 'psalm.xml'
      - 'composer.json'
      - '.github/workflows/static.yml'
  push:
    branches: ['master']
    paths: *paths

permissions:
  contents: read

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  psalm:
    uses: yiisoft/actions/.github/workflows/psalm.yml@master
    with:
      os: >-
        ['ubuntu-latest']
      php: >-
        ['8.0', '8.1', '8.2', '8.3', '8.4', '8.5']

---

## File: .github/workflows/zizmor.yml

name: GitHub Actions Security Analysis with zizmor 🌈

on:
  pull_request:
    paths: &paths
      - '.github/**.yml'
      - '.github/**.yaml'
  push:
    branches: ['master']
    paths: *paths

permissions:
  actions: read # Required by zizmor when reading workflow metadata through the API
  contents: read # Required to read workflow files

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  zizmor:
    uses: yiisoft/actions/.github/workflows/zizmor.yml@master