PHPackages                             torugo/util - 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. torugo/util

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

torugo/util
===========

Library with useful classes and methods

1.12.1(1y ago)0581MITPHPPHP ^8.2

Since Jul 19Pushed 1y ago1 watchersCompare

[ Source](https://github.com/vitor-hugo/util-php)[ Packagist](https://packagist.org/packages/torugo/util)[ RSS](/packages/torugo-util/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (2)Versions (31)Used By (1)

PHP Utility library
====================

[](#php-utility-library-)

Library with useful classes and methods.

Table of Contents
==================

[](#table-of-contents-)

- [Requirements](#requirements)
- [Installation](#installation)
- [Utilities](#utilities)
    - [CDT (Compressed Date and Time)](#cdt-compressed-date-and-time)
        - [get](#get)
        - [fromTimestamp](#fromtimestamp)
        - [fromDateTime](#fromdatetime)
        - [toMicrotime](#tomicrotime)
        - [toDateTime](#todatetime)
    - [DateWriter](#datewriter)
        - [Format options](#format-options)
        - [Internationalization](#internationalization)
        - [Usage](#usage)
    - [SemVer](#semver)
    - [TBase64 (url safe)](#tbase64-url-safe)
    - [TEncrypt](#tencrypt)
        - [Usage](#usage-1)
        - [Cipher algorithm](#cipher-algorithm)
    - [TFile](#tfile)
        - [Check if file exists](#check-if-file-exists)
        - [Create a file](#create-a-file)
        - [Checking if a file is writable](#checking-if-a-file-is-writable)
        - [Load file lines](#load-file-lines)
        - [Parsing .env files](#parsing-env-files)
        - [Parsing .json files](#parsing-json-files)
        - [Parsing .key files](#parsing-key-files)
    - [TPass](#tpass)
        - [Options](#options)
        - [Setting symbols source](#setting-symbols-source)
        - [Checking password strength](#checking-password-strength)
    - [TUID (Torugo Unique ID)](#tuid-torugo-unique-id)
        - [Generating](#generating)
        - [Validating](#validating)
        - [Getting Date and Time](#getting-date-and-time)
    - [TRandom](#trandom)
        - [Random strings](#random-strings)
            - [Parameters](#parameters)
        - [Random Numbers](#random-numbers)
        - [Random Numbers with leading zeros](#random-numbers-with-leading-zeros)
- [Traits](#traits)
    - [Empty Values Trait](#empty-values-trait)
    - [From Array Factory](#from-array-factory)
- [Contribute](#contribute)
- [License](#license)

Requirements
============

[](#requirements)

- PHP 8+
- PHP mbstring extension installed and loaded.
- PHP openssl extension installed and loaded.
- Composer 2+

Installation
============

[](#installation)

On terminal type:

```
composer require torugo/util
```

Or add to your require list on composer.json file:

```
{
    "require": {
        "torugo/util": "^0.1.0"
    }
}
```

Utilities
=========

[](#utilities)

CDT (Compressed Date and Time)
------------------------------

[](#cdt-compressed-date-and-time)

CDT is a way of storing date and time including milliseconds.

```
use Torugo\Util\CDT\CDT;
```

### get

[](#get)

Returns a CDT from current date/time.

```
$cdt = CDT::get(); // returns something like "SGVU9Z2WV"
```

### fromTimestamp

[](#fromtimestamp)

Generates a CDT from a timestamp or [microtime](https://www.php.net/manual/pt_BR/function.microtime.php).

```
$cdt = CDT::fromTimestamp(416410245.1234); // returns "6VX4790YA"
```

### fromDateTime

[](#fromdatetime)

Generates a CDT from a PHP DateTime object.

```
$dateTime = \DateTime::createFromFormat("Y-m-d H:i:s.u", "2017-08-01 14:45:56.789");
$cdt = CDT::fromDateTime($dateTime); // returns "OU0H0K0LX"
```

### toMicrotime

[](#tomicrotime)

Converts a CDT to a microtime (float) number.

```
$micro = CDT::toMicrotime("6VX4790YA"); // returns 416410245.1234
```

### toDateTime

[](#todatetime)

Converts a CDT to a PHP DateTime object.

```
$dateTime = CDT::toDateTime("6VX4790YA"); // returns an instance of DateTime
```

---

DateWriter
----------

[](#datewriter)

Transforms DateTime objects to written date/time.

```
$dw = new DateWriter( \DateTime $dt, string $language );
$dw->write(string $format);
```

### Format options

[](#format-options)

Accepts all PHP [`DateTimeInterface::format`](https://www.php.net/manual/en/datetime.format.php) characters.

Everything in brackets (`[]`) will not change in any way.

By default, all names of months and days of the week are defined as title case, to transform the cases use the markings:

- `*{ ... }` To convert to uppercase.
- `%{ ... }` To convert to lowercase.

### Internationalization

[](#internationalization)

Languages available to write the names of months and days of the week.

OptionLanguageExamples'de'Deutsch"Januar" ... "Dezember" / "Montag" ... "Sonntag"'en'English"January" ... "December" / "sunday" ... "saturday"'es'Spanish"Enero" ... "Diciembre" / "Domingo" ... "Sábado"'fr'French"Janvier" ... "Décembre" / "Dimanche" ... "Samedi"'pt'Portuguese"Janeiro" ... "Dezembro" / "Domingo" ... "Sábado"### Usage

[](#usage)

```
use Torugo\Util\DateWriter\DateWriter;

$dateTime = \DateTime::createFromFormat("Y-m-d H:i:s", "2017-08-01 15:30:45");
$dw = new DateWriter($dateTime, "pt");

$dw->write("[São Paulo,] j [de] %{F} [de] Y");
// São Paulo, 1 de agosto de 2017

$dw->write("*{l}");
// TERÇA-FEIRA
```

---

SemVer
------

[](#semver)

Validates and compare semantic version numbers. The version number must follow [semver.org rules](https://semver.org)

### Usage

[](#usage-)

```
use Torugo\Util\SemVer\SemVer;

$version = new SemVer("1.0.0");

$version->compareTo("1.0.0");      // returns VersionComparison::Equal
$version->compareTo("1.0.1");      // returns VersionComparison::Smaller
$version->compareTo("1.0.0-beta"); // returns VersionComparison::Bigger
```

---

TBase64 (url safe)
------------------

[](#tbase64-url-safe)

Encodes and decodes strings to Base64 that can be used on URLs.

### Usage

[](#usage--1)

```
use Torugo\Util\TBase64\TBase64;

$b64 = TBase64::encode("My String"); // => "TXkgU3RyaW5n"
$decoded = TBase64::decode($b64); // => "My String"
```

---

TEncrypt
--------

[](#tencrypt)

Encrypts/Decrypts strings using symmetric keys.

Note

**Symmetric key:**
Means that the key used for encryption must be the same for decryption.
Each cipher algorithm has a minimum key length in bytes, check the table bellow.

### Usage

[](#usage-1)

```
use Torugo\Util\TEncrypt\TEncrypt;
use Torugo\Util\TEncrypt\Enums\TCipher;

$text = "May the force be with you!";
$key = "ye-PaJYnFPluROpIFo146zhQNvKHbUkIKNMc2rkd8rE";

$encrypted = TEncrypt::encrypt($text, $key,);  // Encrypts the text
$decrypt = TEncrypt::decrypt($encrypted,$key); // Decrypts the encrypted text
```

### Cipher algorithm

[](#cipher-algorithm)

Use the TCipher enum to set a new cipher algorithm.

**Setting the cipher algorithm**:

```
TEncrypt::setCipher(TCipher::CAMELLIA_256_OFB);
```

List of all supported cipher algorithms, default is `AES_256_CFB`.

AlgorithmMin key length in bytesAES\_128\_CBC16AES\_128\_CFB16AES\_128\_CFB116AES\_128\_CFB816AES\_128\_CTR16AES\_128\_OFB16AES\_128\_WRAP\_PAD16AES\_192\_CBC24AES\_192\_CFB24AES\_192\_CFB124AES\_192\_CFB824AES\_192\_CTR24AES\_192\_OFB24AES\_192\_WRAP\_PAD24AES\_256\_CBC32**AES\_256\_CFB**32AES\_256\_CFB132AES\_256\_CFB832AES\_256\_CTR32AES\_256\_OFB32AES\_256\_WRAP\_PAD32ARIA\_128\_CBC16ARIA\_128\_CFB16ARIA\_128\_CFB116ARIA\_128\_CFB816ARIA\_128\_CTR16ARIA\_128\_OFB16ARIA\_192\_CBC24ARIA\_192\_CFB24ARIA\_192\_CFB124ARIA\_192\_CFB824ARIA\_192\_CTR24ARIA\_192\_OFB24ARIA\_256\_CBC32ARIA\_256\_CFB32ARIA\_256\_CFB132ARIA\_256\_CFB832ARIA\_256\_CTR32ARIA\_256\_OFB32CAMELLIA\_128\_CBC16CAMELLIA\_128\_CFB16CAMELLIA\_128\_CFB116CAMELLIA\_128\_CFB816CAMELLIA\_128\_CTR16CAMELLIA\_128\_OFB16CAMELLIA\_192\_CBC24CAMELLIA\_192\_CFB24CAMELLIA\_192\_CFB124CAMELLIA\_192\_CFB824CAMELLIA\_192\_CTR24CAMELLIA\_192\_OFB24CAMELLIA\_256\_CBC32CAMELLIA\_256\_CFB32CAMELLIA\_256\_CFB132CAMELLIA\_256\_CFB832CAMELLIA\_256\_CTR32CAMELLIA\_256\_OFB32CHACHA2032DES\_EDE\_CBC16DES\_EDE\_CFB16DES\_EDE3\_CFB24DES\_EDE3\_CFB124DES\_EDE3\_CFB824DES\_EDE3\_OFB24SM4\_CBC16SM4\_CFB16SM4\_CTR16SM4\_OFB16---

TFile
-----

[](#tfile)

Manipulates text files parsing its content.

```
use Torugo\Util\TFile\TFile;
```

### Check if file exists

[](#check-if-file-exists)

The static method `exists` returns if a file exists in a given path, you can use the argument `createIfNotExists` to create a file if it not exist.

```
TFile::exists(string $path, bool $createIfNotExists): bool
```

### Create a file

[](#create-a-file)

The static method `create` tries to create a file on a given path.
Returns `true` on success or `false` if not.

```
TFile::create(string $path): bool
```

### Checking if a file is writable

[](#checking-if-a-file-is-writable)

```
$file = new TFile(__DIR__ . "/file.txt");

$isWritable = $file->isWritable();
```

### Load file lines

[](#load-file-lines)

Returns the lines of a text file as an array

```
$file = new TFile(__DIR__ . "/file.txt");

$lines = $file->getLines();
```

### Parsing .env files

[](#parsing-env-files)

Parses the content of an `env` file as an associative array.

```
$file = new TFile(__DIR__ . "/.env");

$env = $file->parseEnv();
```

### Parsing .json files

[](#parsing-json-files)

Loads a JSON file content and returns it as an associative array.
In case of invalidation returns an empty array.

```
$file = new TFile(__DIR__ . "/file.json");

$json = $file->parseJson();
```

### Parsing .key files

[](#parsing-key-files)

Loads a .key file content and returns the key from it.

The key file, is a text file that contains a key splitted in lines.
The key MUST be surrounded by `-----BEGIN-----` and `-----END-----`.

**.key file example**

```
-----BEGIN-----
UjNbMRDfsFyfEtgMVXUhhUqNiIEWxNyChFzuTRFwWgupYgbgnseckyLXmQTzjdyf
nQnmKFAiPQCyTjpqiBlewFUPdBlViQejeCZaLlLvbzLSAZgKUcRDWGqiPCrxhprO
BozroybWrtgzUfkdQbDzukaEidtADbsQQUTteFSIlNvyrrbbYJpzAkFrGiexsjOb
sSSwNsYcCzyRTDQoJIemWtGAJMyPSTJoaGTbShtJejVRmhPwpmcTFImkaKXIPNnl
HOQKUDnhoDQFXVsFueCFXRfrEPiieJSJUEGBmmCJFoMFNOsEVgoXIPMVyaFiZgbi
vZNKyydWKNXqrJfvWwHZPnTvIyGRzgqicEjdnNrlqsLYmKCpjeuVmvteBSIZCuLs
KlcqBtYhbeoTfUesqTwGDftjjSFHNWHirwWPdusiGUqDzjlzJPiaBsosBFyeziHb
kaEdZEpTOUoRYiFAmtiVHqPFFfwxytrzQkwfoGORYviXdyfRYYfcOLKZlwoDUMnm
dsUrbfhhScMFUrPtRijXiuTwkcyacOTojJEvtafFgiETIPzHfvNiXFFxYmNhbftJ
hMwvJQpYwykHNekNYFJbIfepGErQrAxuDSeOddKKgYoDfSeZzbPeabrtavJWjXgb
wSQPVFBJtyEBuyQilRHKQduJOKOBYuwOhlWvJzqxeywCAaAYFyVtHcSFjyxYVgzy
rKjtjbJnAyyfkAUZawctbPqfCkqovijpoomjLsPIYWOMLkdfyktwCorpbKayFEnJ
OIiGAamMuGMheNadiGJGIAvwJIOcnAugRmiCKFbDWdSgGZZHjdeUbZyEJMJxzPcx
ZKKQEfQqIAZSpGSaKHNsfBLKMhRkEmqIkKTopzPJisPalGJqobiaGMifFPwnzHNd
RCRWklziDGeAbLZAVwByJpFHShtPETUcypXgWNTECHhxsveQtgFqPWqEPQPyFsfW
OrHzAMARDiHywWmmeLGyrrJDTnuXClvVIKvTuUQXwXymnqDmroUXRMbuykvcaGPP
-----END-----

```

```
$file = new TFile(__DIR__ . "/mykey.key");

$key = $file->parseKeyFile();
```

---

TPass
-----

[](#tpass)

Generates random passwords, and checks password strength

```
use Torugo\Util\TPass\TPass;
```

### Options

[](#options)

OptionTypeDefaultDescriptionincludeLowercasebooltrueInclude lowercased lettersincludeUppercasebooltrueInclude uppercased lettersincludeNumbersbooltrueInclude numeric charactersincludeSymbolsbooltrueInclude special charactersbeginWithALetterboolfalsePassword should begin with a letterNote

When enabling `beginWithALetter` assure that `includeLowercase` or `includeUppercase` is enabled.

### Setting symbols source

[](#setting-symbols-source)

The default symbols source is `!;#$%&()*+,-./:;?@[]^_{|}~`;

To set a custom symbols source, use the method `setSymbols`.

### Checking password strength

[](#checking-password-strength)

To check the password strength use the method `checkPasswordStrength`;

It returns an int value from 0 to 4, where:

```
0 = Very week
1 = week
2 = medium
3 = strong
4 = very strong

```

**Examples**

```
"123456" => 0,
"112233" => 0,
"admin" => 0,
"password" => 0,
"psw1223!A" => 1,
"NU$;K^9" => 2,
"NU$;k3+" => 3,
"NU$;K^+B#D!;+D%8nP" => 4,
"123456NU$;K^+B#D!;+D%8nP" => 4,

```

---

TUID (Torugo Unique ID)
-----------------------

[](#tuid-torugo-unique-id)

Generates a randomic unique ID with date and time.

```
use Torugo\Util\TUID\TUID;
```

This tool can generate three types of IDs:

TypeLengthSampleShort20QJLM77R-TS0SHULDI0SHMedium26KMSEEBAN-NC7V-TM0SHULDI0U2Long36PVA4M433-20L5-K1HVUPLQW-TL0SHULDI0VT### Generating

[](#generating)

```
$short = TUID::short();
$medium = TUID::medium();
$long = TUID::long();
```

### Validating

[](#validating)

```
$tuid = "PVA4M433-20L5-K1HVUPLQW-TL0SHULDI0VT";
TUID::validate($tuid); // returns true
```

### Getting Date and Time

[](#getting-date-and-time)

```
$tuid = "PVA4M433-20L5-K1HVUPLQW-TL0SHULDI0VT";
TUID::getDateTime($tuid); // returns a PHP DateTime instance
```

---

TRandom
-------

[](#trandom)

Generates random strings and numbers

```
use Torugo\Util\TRandom\TRandom;

$tRandom = new TRandom;
```

### Random strings

[](#random-strings)

Sets the source chars used to generate random strings.

```
$rnd = $tRandom->string(10); // Generates 10 chars long random string
```

#### Parameters

[](#parameters)

ParameterTypeDefaultDescription`alpha`stringa...zA...ZAlphabetical characters used to generate strings.`numbers`string0123456789Numerical characters used to generate strings.`symbols`string!;#%&amp;()\*+,-./:;&lt;=&gt;?@\[\]^\_{|}~Special characters used to generate strings.`includeAlpha`booltrueShould include alphabetical chars.`includeNumbers`booltrueShould include numbers.`includeSymbols`booltrueShould include symbols.`startWithAlphaChar`boolfalseShould start with alphabetical characters.#### Setting the source characters

[](#setting-the-source-characters-)

```
$random->alpha = "ABCDEF";
$random->numbers = "123";
$random->symbols = "#$%&*";

$str = $random->string(10);
// Generates a random string with the given characters.
```

### Random Numbers

[](#random-numbers)

Generates a random integer between the given range.

```
$tRandom->number(1001, 9999); // Generates a random number between 1001 and 9999
```

### Random Numbers with leading zeros

[](#random-numbers-with-leading-zeros)

Generates a positive random integer with leading zeros.

```
$tRandom->lzNumber(1, 9999, 4); // 0001 ... 9999
$tRandom->lzNumber(1001, 999999, null); // 001001 ... 999999
```

---

Traits
======

[](#traits)

Empty Values Trait
------------------

[](#empty-values-trait)

Returns an empty value for a specific type.

```
use Torugo\Util\Traits\EmptyValues;

class MyClass {
    use EmptyValues;

    function myFunction() {
        // ...
        $type = $this->getEmptyValueForType(gettype($var));
        // ...
    }
}
```

From Array Factory
------------------

[](#from-array-factory)

Instantiates a class from a key=&gt;value array.

1. The keys must be equal to the properties names.
2. All properties must be setted as public.

### Example

[](#example-)

```
use Torugo\Util\Traits\FromArrayFactory;

class UserDto
{
    use FromArrayFactory;

    public string $name;
    public string $email;
    public string $password;
}

$payload = [
    "name" => "Full User Name",
    "email" => "user@gmail.com",
    "password" => "SuperStrongPassword!",
];

$instance = UserDto::fromArray($payload);
// $instance->name ==> "Full User Name"
// $instance->email ==> "user@gmail.com"
// $instance->password ==> "SuperStrongPassword!"
```

Contribute
==========

[](#contribute)

It is currently not open to contributions, I intend to make it available as soon as possible.

License
=======

[](#license)

This library is licensed under the MIT License - see the LICENSE file for details.

###  Health Score

31

—

LowBetter than 68% of packages

Maintenance35

Infrequent updates — may be unmaintained

Popularity8

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 100% 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 ~2 days

Total

30

Last Release

607d ago

Major Versions

0.2.0 → 1.0.02024-07-22

### Community

Maintainers

![](https://www.gravatar.com/avatar/94c7a8fd24b1105482b6df73fd33e1acc96372eac305a42669e08f24097a65ec?d=identicon)[torugo](/maintainers/torugo)

---

Top Contributors

[![vitor-hugo](https://avatars.githubusercontent.com/u/32072927?v=4)](https://github.com/vitor-hugo "vitor-hugo (119 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/torugo-util/health.svg)

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

###  Alternatives

[spatie/robots-txt

Determine if a page may be crawled from robots.txt and robots meta tags

25416.4M23](/packages/spatie-robots-txt)

PHPackages © 2026

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