PHPackages                             sandromiguel/php-type - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Validation &amp; Sanitization](/categories/validation)
4. /
5. sandromiguel/php-type

ActiveLibrary[Validation &amp; Sanitization](/categories/validation)

sandromiguel/php-type
=====================

Validate PHP field values to ensure data integrity and suppress linter alerts.

v1.2.0(2y ago)153MITPHPPHP &gt;=8.1

Since Nov 29Pushed 2y ago1 watchersCompare

[ Source](https://github.com/SandroMiguel/php-type)[ Packagist](https://packagist.org/packages/sandromiguel/php-type)[ Docs](https://github.com/SandroMiguel/php-type)[ RSS](/packages/sandromiguel-php-type/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (3)Dependencies (9)Versions (6)Used By (0)

PhpType
=======

[](#phptype)

[![license](https://camo.githubusercontent.com/59497bc4563dd468e37bbf539439e60cacf196f537f678b721a8efabf21c64ef/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4c6963656e73652d4d49542d626c75652e7376673f7374796c653d666c6174)](LICENSE)

PhpType is a PHP library meticulously crafted for validating field values, safeguarding data integrity, and quelling linter alerts. It goes beyond mere linting concerns by seamlessly incorporating runtime checks. These runtime checks act as a robust validation layer during code execution, ensuring that your data aligns with the specified types. This dual approach not only suppresses linter warnings but also fortifies your application's integrity, instilling an extra level of confidence in your data handling processes.

Features
--------

[](#features)

- Supports the `int`, `string`, `bool`, and `array` data types.
- Provides a simple and easy-to-use interface.
- Is lightweight and efficient.
- Is well-documented.

Requirements
------------

[](#requirements)

- PHP 8.1 or higher

Table of Contents
-----------------

[](#table-of-contents)

- [Installation](#installation)
- [Usage](#usage)
- [Public Methods](#public-methods)
- [Frequently Asked Questions (FAQ)](#frequently-asked-questions-faq)
- [Credits](#credits)
- [Contributing](#contributing)
- [License](#license)

Installation
------------

[](#installation)

You can install this library via Composer. Run the following command:

```
composer require sandromiguel/php-type
```

Usage
-----

[](#usage)

This library excels in validating arrays, ensuring that data adheres to specified types and contributing to a more robust and reliable codebase. Consider the following scenarios where PhpType proves beneficial:

#### Scenario 1: Method Input Validation

[](#scenario-1-method-input-validation)

When accepting arrays as method parameters, it's crucial to validate the input to guarantee that the data aligns with the expected types. Using PhpType in such scenarios enhances code reliability and prevents unexpected type mismatches.

Example thats shows a linter warning:

```
    /**
     * @param array $someArray The array.
     */
    public static function someMethodWithWarning(array $someArray): void
    {
        $someEntity = new Entity(
            $someArray['someInt'],
            $someArray['someString']
        );
        echo $someEntity->getProperty1() . "\n";
        echo $someEntity->getProperty2() . "\n";
    }
```

Address the previous warning with PhpType:

```
    /**
     * @param array $someArray The array.
     */
    public static function someMethodWithPhpType(array $someArray): void
    {
        $someInt = Validator::validate('someInt', $someArray['someInt'])->getIntValue();
        $someString = Validator::validate('someString', $someArray['someString'])->getStringValue();

        $someEntity = new Entity($someInt, $someString);
        echo $someEntity->getProperty1() . "\n";
        echo $someEntity->getProperty2() . "\n";
    }
```

#### Scenario 2: Method Output Validation

[](#scenario-2-method-output-validation)

In situations where it is necessary to return values from an array, such as strings, PhpType ensures that the returned values adhere to the expected types.

```
use PhpType\Validator;

/**
 * Get some text.
 *
 * @return string The text.
 */
public function getSomeText(): string
{
    return Validator::validate(
        'fieldName',
        $this->params['fieldName'] ?? null
    )
        ->stringNotEmpty()
        ->getStringValue();
}
```

Public Methods
--------------

[](#public-methods)

- **`validate(string $fieldName, mixed $fieldValue): Validator`**Start the validation chain for a field.
- **`stringNotEmpty(): Validator`**Check if the string is not empty.
- **`getArrayValue(): array`**Get the array value.
- **`getArrayValueOrNull(): ?array`**Get the array value or null.
- **`getBoolValue(): bool`**Get the boolean value.
- **`getBoolValueOrNull(): ?bool`**Get the boolean value or null.
- **`getIntValue(): int`**Get the integer value.
- **`getIntValueOrNull(): ?int`**Get the integer value or null.
- **`getStringValue(): string`**Get the string value.
- **`getStringValueOrNull(): ?string`**Get the string value or null.
- **`getValue(): mixed`**Get the mixed value.

Frequently Asked Questions (FAQ)
--------------------------------

[](#frequently-asked-questions-faq)

### Q: Why use PhpType when linters like Psalm or PHPStan already exist?

[](#q-why-use-phptype-when-linters-like-psalm-or-phpstan-already-exist)

**A:** While linters are powerful tools, PhpType serves as a lightweight solution specifically designed to handle scenarios where linter warnings arise due to type mismatches in array structures. It provides a simple and easy-to-use interface, offering an alternative approach to address such issues.

### Q: Can I use PhpType in production code?

[](#q-can-i-use-phptype-in-production-code)

**A:** Yes, PhpType is intended for use in production code. It is perfectly suitable for production use without any issues.

### Q: Why not use deserialization libraries like symfony/serializer for handling array data?

[](#q-why-not-use-deserialization-libraries-like-symfonyserializer-for-handling-array-data)

**A:** Deserialization libraries like symfony/serializer are excellent for handling complex data structures by converting them into objects. PhpType is more suited for scenarios where direct manipulation of arrays is necessary, such as dealing with legacy code or situations where immediate refactoring is not feasible.

### Q: How do I handle linter warnings with PhpType?

[](#q-how-do-i-handle-linter-warnings-with-phptype)

**A:** PhpType helps eliminate linter warnings by providing a straightforward method for validating array values, ensuring type correctness, and suppressing alerts from linters like PHPStan. Check the documentation for examples and usage details.

Credits
-------

[](#credits)

- [EditorConfig](https://editorconfig.org/): IDE coding style settings.
- [PHPUnit](https://phpunit.de/): Testing framework for PHP.
- [PHP CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer): PHP coding standards checker and fixer.
- [PHP Insights](https://phpinsights.com/): Code quality and architecture analysis tool.
- [PHP Metrics](https://phpmetrics.org/): PHP metrics generator.
- [PHPStan](https://phpstan.org/): PHP static analysis tool.
- [Psalm](https://psalm.dev/): Static analysis tool for PHP.
- [Composer](https://getcomposer.org/): Dependency management for PHP.

Contributing
------------

[](#contributing)

Want to contribute? All contributions are welcome. Read the [contributing guide](CONTRIBUTING.md).

Questions
---------

[](#questions)

If you have questions tweet me at [@sandro\_m\_m](https://twitter.com/sandro_m_m) or [open an issue](https://github.com/SandroMiguel/php-type/issues/new).

License
-------

[](#license)

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details

\*\*~ sharing is caring ~\*\*

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity12

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity55

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 83.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~54 days

Total

3

Last Release

782d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/6b082015ff3afef14c40ed5af8887ccaf378c6eaabd15aac38103ecdb5b0dc4f?d=identicon)[sandromiguel](/maintainers/sandromiguel)

---

Top Contributors

[![SandroMiguel](https://avatars.githubusercontent.com/u/6423157?v=4)](https://github.com/SandroMiguel "SandroMiguel (15 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (3 commits)")

---

Tags

phptypevalidationlibraryfieldPHP Library

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan, Psalm

Type Coverage Yes

### Embed Badge

![Health badge](/badges/sandromiguel-php-type/health.svg)

```
[![Health](https://phpackages.com/badges/sandromiguel-php-type/health.svg)](https://phpackages.com/packages/sandromiguel-php-type)
```

###  Alternatives

[inhere/php-validate

generic data validate, filter library of the php

26787.4k13](/packages/inhere-php-validate)[blakvghost/php-validator

PHPValidator is a modern PHP library for data validation in your PHP applications. It provides a flexible and extensible way to validate data using predefined rules or by creating custom validation rules.

2524.2k2](/packages/blakvghost-php-validator)[eftec/validationone

It's a php library for fetch and validate fields

113.8k2](/packages/eftec-validationone)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
