PHPackages                             pkdev/traits - 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. [Utility &amp; Helpers](/categories/utility)
4. /
5. pkdev/traits

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

pkdev/traits
============

Traits developed by PkDev for use in all projects

v2.0.1(2w ago)177[1 PRs](https://github.com/pkdev-labs/pkdev-traits/pulls)1MITPHPPHP ^8.3CI passing

Since Jan 22Pushed 4d ago1 watchersCompare

[ Source](https://github.com/pkdev-labs/pkdev-traits)[ Packagist](https://packagist.org/packages/pkdev/traits)[ RSS](/packages/pkdev-traits/feed)WikiDiscussions develop Synced yesterday

READMEChangelog (7)Dependencies (3)Versions (10)Used By (1)

 [![PkDev Logo](https://camo.githubusercontent.com/00d413dfb6c189d260f02694263b4a4b455fe27a34e1b22627e047d65aeebcf1/68747470733a2f2f706b73332e6e7963332e63646e2e6469676974616c6f6365616e7370616365732e636f6d2f706b6465765f6c6f676f5f656c657068616e745f6c6f6e672e706e67)](https://www.pkdev.dev)

[![Tests](https://github.com/pkdev-labs/pkdev-traits/actions/workflows/phpunit-tests.yml/badge.svg)](https://github.com/pkdev-labs/pkdev-traits/actions/workflows/phpunit-tests.yml/badge.svg)[![Code Quality](https://github.com/pkdev-labs/pkdev-traits/actions/workflows/quality.yml/badge.svg)](https://github.com/pkdev-labs/pkdev-traits/actions/workflows/quality.yml/badge.svg)[![codecov](https://camo.githubusercontent.com/a49222329bb9d2447164804a961dceb1e6c254df8a2f7f52135d2de402d308dc/68747470733a2f2f636f6465636f762e696f2f67682f706b6465762d6c6162732f706b6465762d7472616974732f6272616e63682f6d61737465722f67726170682f62616467652e737667)](https://codecov.io/gh/pkdev-labs/pkdev-traits)[![Latest Stable Version](https://camo.githubusercontent.com/7facaa6aa7314054d5c9faba064c64d4d63284552681424611e6835b436ee3b7/68747470733a2f2f706f7365722e707567782e6f72672f706b6465762f7472616974732f76)](https://packagist.org/packages/pkdev/traits)[![License](https://camo.githubusercontent.com/a3094c517654dd8af3ce6a92110d911f58a892c3b841845a5f89fd85ae1e6d9c/68747470733a2f2f706f7365722e707567782e6f72672f706b6465762f7472616974732f6c6963656e7365)](https://packagist.org/packages/pkdev/traits)

About Project
-------------

[](#about-project)

**PkDev Traits** is an open-source collection of small, dependency-free PHP traits that centralize the reusable helpers used across PkDev projects — validation, sanitization, dates, strings, arrays, numbers, encryption, hashing, UUIDs, and JSON. Every method is `public static`, so you can either `use` a trait into a class or call it directly.

The library is built test-first: the suite runs at **100% code coverage**, is statically analyzed by **PHPStan at the maximum level**, and is checked against **PSR-12** on every push.

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

[](#requirements)

- **PHP 8.3+**
- `ext-openssl` (used by `EncryptionTrait`)

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

[](#installation)

```
composer require pkdev/traits
```

Available Traits
----------------

[](#available-traits)

All traits live under the `PkDev\Traits` namespace.

TraitPurposeMethods`ValidationTrait`Validate untrusted input`validateRequired`, `validateEmail`, `validateNumeric`, `validateInteger`, `validateFloat`, `validateMaxLength`, `validateMinLength``SanitizeTrait`Clean untrusted input`sanitizeString`, `sanitizeEmail`, `sanitizeInteger`, `sanitizeFloat`, `sanitizeURL``StringTrait`String manipulation`slugify`, `truncate`, `limitWords`, `mask`, `toCamelCase`, `toSnakeCase`, `toTitleCase`, `startsWith`, `endsWith`, `contains``ArrayTrait`Array access &amp; shaping`get`, `has`, `set` (dot-notation), `pluck`, `first`, `last`, `flatten`, `only`, `except`, `groupBy``NumberTrait`Number formatting`formatCurrency`, `percentage`, `ordinal`, `clamp`, `humanReadableBytes`, `abbreviate``DateTrait`Date helpers`formatDate`, `addDaysToDate`, `isFutureDate`, `isPastDate`, `getDaysDifference`, `areDatesEqual`, `isWeekend``EncryptionTrait`AES-256 encryption`getEncryptionKey`, `generateEncryptionKey`, `encryptData`, `decryptData``HashTrait`Password &amp; HMAC hashing`hashPassword`, `verifyPassword`, `hmac``UuidTrait`UUID generation &amp; validation`uuid4`, `isUuid``JsonTrait`Safe JSON encode/decode`encode`, `decode`, `isValidJson``HelperTrait`Misc utilities`generateRandomString`Usage
-----

[](#usage)

```
use PkDev\Traits\ValidationTrait;

class SignupForm
{
    use ValidationTrait;

    public function isValid(string $email): bool
    {
        return self::validateEmail($email);
    }
}
```

A taste of each trait:

```
use PkDev\Traits\StringTrait;
use PkDev\Traits\ArrayTrait;
use PkDev\Traits\NumberTrait;
use PkDev\Traits\SanitizeTrait;
use PkDev\Traits\DateTrait;
use PkDev\Traits\UuidTrait;
use PkDev\Traits\JsonTrait;
use PkDev\Traits\HashTrait;

class Demo
{
    use StringTrait, ArrayTrait, NumberTrait, SanitizeTrait, DateTrait, UuidTrait, JsonTrait, HashTrait;

    public function examples(): void
    {
        // StringTrait
        self::slugify('Hello World!');            // "hello-world"
        self::mask('4111111111111111');           // "************1111"
        self::toSnakeCase('helloWorld');           // "hello_world"

        // ArrayTrait — dot notation
        $data = ['user' => ['profile' => ['name' => 'Phil']]];
        self::get($data, 'user.profile.name');     // "Phil"
        self::pluck([['id' => 1], ['id' => 2]], 'id'); // [1, 2]

        // NumberTrait
        self::formatCurrency(1234.5);              // "$1,234.50"
        self::ordinal(22);                          // "22nd"
        self::humanReadableBytes(1268777);          // "1.21 MB"

        // SanitizeTrait
        self::sanitizeEmail('  user@example.com '); // "user@example.com"

        // DateTrait
        self::addDaysToDate('2024-01-01', 5);       // "2024-01-06"
        self::isWeekend('2024-01-20');              // true

        // UuidTrait
        self::uuid4();                              // "b1e8...-4...-..."
        self::isUuid('not-a-uuid');                 // false

        // JsonTrait (throws JsonException on failure)
        self::encode(['ok' => true]);               // '{"ok":true}'
        self::isValidJson('{bad}');                 // false

        // HashTrait
        $hash = self::hashPassword('secret');
        self::verifyPassword('secret', $hash);      // true
    }
}
```

Development
-----------

[](#development)

```
git clone https://github.com/pkdev-labs/pkdev-traits.git
cd pkdev-traits
composer install
```

Quality tooling:

```
composer test            # PHPUnit (100% coverage enforced in CI)
composer analyse         # PHPStan, level max
composer check           # test + analyse

# Coding standards run as a standalone PHAR (not a Composer dependency):
php php-cs-fixer.phar fix --dry-run --diff   # check
php php-cs-fixer.phar fix                      # apply
```

Coverage and PHP-CS-Fixer require a coverage driver (`pcov` recommended). PHP-CS-Fixer is intentionally run as a PHAR to keep the dependency tree clean.

Releasing
---------

[](#releasing)

Versions are derived from **git tags** (not a `composer.json` field). To cut a release, tag the merged commit on `master` and push the tag — Packagist updates automatically:

```
git tag v2.0.0
git push origin v2.0.0
```

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

[](#contributing)

Issues and pull requests are welcome. Please keep the suite green (`composer check`), maintain 100% coverage, and run PHP-CS-Fixer before opening a PR.

License
-------

[](#license)

Released under the [MIT License](LICENSE).

Contact
-------

[](#contact)

Questions or just want to say hello? Reach out at .

###  Health Score

49

—

FairBetter than 94% of packages

Maintenance98

Actively maintained with recent releases

Popularity14

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 98% 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 ~145 days

Recently: every ~217 days

Total

7

Last Release

20d ago

Major Versions

1.1.3 → 2.0.02026-06-12

PHP version history (2 changes)1.1.2PHP ^8.1

2.0.0PHP ^8.3

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/391609?v=4)[pkdev](/maintainers/pkdev)[@pkdev](https://github.com/pkdev)

---

Top Contributors

[![WyldHalfling](https://avatars.githubusercontent.com/u/69316827?v=4)](https://github.com/WyldHalfling "WyldHalfling (48 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")

---

Tags

phptraits

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/pkdev-traits/health.svg)

```
[![Health](https://phpackages.com/badges/pkdev-traits/health.svg)](https://phpackages.com/packages/pkdev-traits)
```

###  Alternatives

[omaralalwi/php-builders

sample php traits to add ability to use builder design patterns with easy in PHP applications

153.1k1](/packages/omaralalwi-php-builders)[prevailexcel/laravel-action-service-trait

A simple Laravel package to create actions, traits and services using artisan commands

143.5k](/packages/prevailexcel-laravel-action-service-trait)

PHPackages © 2026

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