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

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

semelapavel/php-util
====================

PHP Utils for easier life.

4.0.3(4y ago)124↓100%MITPHPPHP &gt;=7.4

Since Sep 8Pushed 4y agoCompare

[ Source](https://github.com/SemelaPavel/php-util)[ Packagist](https://packagist.org/packages/semelapavel/php-util)[ Docs](https://github.com/SemelaPavel/php-util)[ RSS](/packages/semelapavel-php-util/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (3)Versions (14)Used By (0)

php-util library
================

[](#php-util-library)

[![Latest Stable Version](https://camo.githubusercontent.com/e7025b5c78b3ccee0f7979b960e2b8063641095aa89cbe77be4ec7565a3f0d41/68747470733a2f2f706f7365722e707567782e6f72672f73656d656c61706176656c2f7068702d7574696c2f76)](https://github.com/SemelaPavel/php-util/releases)[![License](https://camo.githubusercontent.com/b244103f01c52f28ee3e8a39a0b49af10e25705a0588fe9a59d121f52f7e40ba/68747470733a2f2f706f7365722e707567782e6f72672f73656d656c61706176656c2f7068702d7574696c2f6c6963656e7365)](https://github.com/SemelaPavel/php-util/blob/master/LICENSE)

About
-----

[](#about)

PHP-Util library is a set of useful PHP classes that make life easier.

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

[](#installation)

Use the package manager [composer](https://getcomposer.org) to install php-util.

```
composer require semelapavel/php-util
```

Table of contents
-----------------

[](#table-of-contents)

- [Object](#object)
    - [ClassLoader](#objectclassloader)
    - [Byte](#objectbyte)
- [File](#file)
    - [File](#filefile)
    - [FileFilter](#filefilefilter)
- [Http](#http)
    - [FileUpload](#httpfileupload)
- [Pagination](#pagination)
    - [Paginator](#paginationpaginator)
    - [Pagination](#paginationpagination)
- [String](#string)
    - [RegexPattern](#stringregexpattern)
- [Time](#time)
    - [Holidays](#timeholidays)
    - [Calendar](#timecalendar)
    - [LocalDateTime](#timelocaldatetime)

Object
======

[](#object)

Object\\ClassLoader
-------------------

[](#objectclassloader)

A simple PSR-4 autoloader that loads files with required classes using namespaces.

```
$classLoader = new \SemelaPavel\Object\ClassLoader();
$classLoader->addNamespace('MyNamespace', '/src/myApp');
$classLoader->addDirectory('/src/other');
$classLoader->register();
```

In this example, classLoader will try to find each file with a fully-qualified class name starting with the prefix `MyNamespace` in the `/src/myApp` directory: `\MyNamespace\Class` should be found as `/src/myApp/Class.php`.

If the file cannot not be found, or if it does not have `MyNamespace` prefix, the classloader will try to find a file by the fully-qualified class name in `/src/other` directory: `\MyNamespace\Class` should be found as `/src/other/MyNamespace/Class.php`.

Object\\Byte
------------

[](#objectbyte)

This class wraps an integer value and represents it as a binary byte.

```
$byte = new Byte(1024);
echo $byte;                      // 1024
echo $byte->floatValue('KB');    // 1
echo $byte->floatValue('MB', 5); // 0,00098
```

Byte of any value and its specified binary unit:

```
$byte = Byte::from(2.5, 'MB'); // 2621440
```

Easy parsing of php.ini values:

```
$byte = Byte::fromPhpIniNotation(ini_get('upload_max_filesize'));
```

Parsing byte value from any string:

```
$byte = Byte::parse('8');     // 8
$byte = Byte::parse('16B');   // 16
$byte = Byte::parse('1 KiB'); // 1024
$byte = Byte::parse('0,5MB'); // 524288
```

File
====

[](#file)

The File namespace contains a set of classes for working with files.

File\\File
----------

[](#filefile)

An instance of this class represents a file in the file system. The file does not need to exist, or be readable when creating a File object. This class extends [\\SplFileInfo](https://www.php.net/manual/en/class.splfileinfo.php) class from **Standard PHP Library** (SPL).

```
$file = new File('file.txt');
echo $file->getMimeType();       // 'text/plain'
$content = $file->getContents(); // Reads the file and returns its contents as a string.
```

Check if the file name is safe and valid for most used operating systems:

```
$file->hasValidName(); // Returns true in this example.
```

and without creating an object:

```
File::isValidFileName('file.txt/'); // false
```

Strip the ASCII control characters, whitespaces, slashes, dots and backslashes from the end of file name:

```
File::rtrimFileName('file.txt/'); // Returns 'file.txt' in this example.
```

File\\FileFilter
----------------

[](#filefilefilter)

An instance of this class helps filter out unwanted files by file names using shell wildcards or a regular expression, files with a file size out of set size or range and files with specific date and time or date-time range.

```
$filter = new FileFilter();
$filter->setFileNameWhiteList(['*.jpg', '*.png', '*.gif']);
$filter->setFileNameBlackList(['*.php.*']);
$filter->setFileNameRegex(new \SemelaPavel\String\RegexPattern('^[^0-9]*$'));
$filter->setFileSize('>1 KB < 1 MB');
$filter->setMTime('>= 2021-01-01 < 2021-01-02 12:00');
```

Lets have `image.jpg` with file size `4 KB` and modif. time `2021-01-01`:

```
$filter->fileNameMatch('image.jpg')        // true
$filter->compareFileSize(4096);            // true
$filter->compareMTime('2021-01-01 13:37'); // true
```

Http
====

[](#http)

The Http namespace contains a set of classes handling requests and responses over HTTP.

Http\\FileUpload
----------------

[](#httpfileupload)

The `FileUpload` provides basic functionality for retrieving normalized file upload data for further processing. Each leaf of the files array is an instance of `UploadedFile` or `null` if error `UPLOAD_ERR_NO_FILE` occured.

See simplified code below:

```

    Select file to upload:

    Select file to upload:

    Select file to upload:

```

```
$upload = new FileUpload();
$files = $upload->getUploadedFiles();

if ($files['file']) {
    $files['file']->move(dirname(__DIR__) . '/upload/', 'newFile.txt'); // move the file with rename
}

if ($files['filesArray'][0]) {
    $files['filesArray'][0]->move(dirname(__DIR__) . '/upload/');
}
```

Pagination
==========

[](#pagination)

A set of useful classes for managing pagination of your web pages.

Pagination\\Paginator
---------------------

[](#paginationpaginator)

Simple pagination calculator to help with calculate number of pages for specific number of items, number of items per page, offset etc. See example below with total number of items set to 100, items per page set to 5 and current page set to 5.

```
$paginator = new Paginator(100, 5, 5);

$paginator->getCurrentPage();       // 5
$paginator->getNumOfPages();        // 20
$paginator->getCurrentPageLength(); // 5 = number of page items
$paginator->getOffset();            // 20 = current page contains items nr. 21-25
$paginator->getFirstPage();         // 1
$paginator->getLastPage();          // 20
$paginator->isFirst();              // false
$paginator->isLast();               // false
$paginator->getNextPage();          // 6
$paginator->getPrevPage();          // 4
```

Pagination\\Pagination
----------------------

[](#paginationpagination)

`Paginator` extension that adds method to get an array of pages for advanced pagination. See example below with total number of items set to 100, items per page set to 5 and current page set to 5.

```
$pagination = new Pagination(100, 5, 5);
$pages = $pagination->toArray(1, 2);
```

The `$pages` array structure will looks like:

```
[
    ['page' => 1, 'isCurrent' => false],
    ['page' => null, 'isCurrent' => false],
    ['page' => 3, 'isCurrent' => false],
    ['page' => 4, 'isCurrent' => false],
    ['page' => 5, 'isCurrent' => true],
    ['page' => 6, 'isCurrent' => false],
    ['page' => 7, 'isCurrent' => false],
    ['page' => null, 'isCurrent' => false],
    ['page' => 20, 'isCurrent' => false]
]
```

String
======

[](#string)

String\\RegexPattern
--------------------

[](#stringregexpattern)

This class represents a regular expression pattern.

Simple pattern example:

```
$pattern = new RegexPattern('[a-z]{3}', RegexPattern::CASE_INSENSITIVE);

if ($pattern->isValid()) {
    \preg_match((string) $pattern, 'aBc');  // 1
    $pattern->match('aBc');                 // true
}
```

Pattern with bind example:

```
$pattern = new RegexPattern('[a-z]{3}bind', 0, array('bind' => '.value'));
echo $pattern; // ~[a-z]{3}\.value~
```

Time
====

[](#time)

Time\\Holidays
--------------

[](#timeholidays)

`ArrayAccess` class which handles holidays and provides some extra functionality.

```
$holidays = new Holidays();
$holidays[Holidays::goodFriday(2021)] = "Good Friday";
$holidays[Holidays::easterMonday(2021)] = "Easter Monday";
$holidays["2021-05-01"] = "May Day";

echo $holidays['2021-05-01']; // "May Day"

foreach ($holidays->toArray() as $date => $description) {
    echo $date . ': ' . $description . '';
}
```

Time\\Calendar
--------------

[](#timecalendar)

This class helps with date calculations.

```
$today = new \DateTime();
Calendar::isDayOff($today);
$prevWorkday = Calendar::prevWorkday($today);
$nextWorkday = Calendar::nextWorkday($today);
$lastDayOfPrevMonth = Calendar::lastDayOfPrevMonth($today);
$lastDayOfMonth = Calendar::lastDayOfMonth($today);
```

With `Holidays` object set:

```
$holidays = new Holidays();
$holidays["2021-05-01"] = "May Day";

$today = new \DateTime();
Calendar::isDayOff($today, holidays);
$prevWorkday = Calendar::prevWorkday($today, holidays);
$nextWorkday = Calendar::nextWorkday($today, holidays);
```

Time\\LocalDateTime
-------------------

[](#timelocaldatetime)

This class is a `DateTime` factory. All functions in this class use default time zone.

```
LocalDateTime::setLocalTimeZone(new \DateTimeZone('Europe/Prague'));

$dateTimeStr = ' 2020-  07 - 06 T 13 :37 : 00 . 001337  + 02: 00 ';
$normalizedDateTimeStr = LocalDateTime::normalize($dateTimeStr); // "2020-07-06T13:37:00.001337+02:00"

$localDateTime = LocalDateTime::parse($normalizedDateTimeStr);
$now = LocalDateTime::now();
$today = LocalDateTime::today();

$now->format(LocalDateTime::SQL_DATETIME)  // 'Y-m-d H:i:s' format
```

###  Health Score

27

—

LowBetter than 49% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity10

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity61

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 ~24 days

Total

13

Last Release

1775d ago

Major Versions

1.1.0 → 2.0.02020-09-26

2.2.1 → 3.0.02021-02-23

3.1.0 → 4.0.02021-03-31

PHP version history (2 changes)v1.0.0PHP &gt;=5.6

4.0.0PHP &gt;=7.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/948a94d34226ff0f4b37a32f4961aeb1357c9cf50ab656c8a14f34f006018c4b?d=identicon)[SemelaPavel](/maintainers/SemelaPavel)

---

Top Contributors

[![SemelaPavel](https://avatars.githubusercontent.com/u/11814553?v=4)](https://github.com/SemelaPavel "SemelaPavel (22 commits)")

---

Tags

paginationregexfile-uploaddate-timeclass loader

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[composer/pcre

PCRE wrapping library that offers type-safe preg\_\* replacements.

693313.8M34](/packages/composer-pcre)[wenzhixin/bootstrap-table

An extended table to integration with some of the most widely used CSS frameworks. (Supports Bootstrap, Semantic UI, Bulma, Material Design, Foundation)

11.8k283.4k1](/packages/wenzhixin-bootstrap-table)[spatie/regex

A sane interface for php's built in preg\_\* functions

1.1k17.1M59](/packages/spatie-regex)[babdev/pagerfanta-bundle

Bundle integrating Pagerfanta with Symfony

20817.8M65](/packages/babdev-pagerfanta-bundle)[gherkins/regexpbuilderphp

PHP port of thebinarysearchtree/regexpbuilderjs

1.4k163.0k1](/packages/gherkins-regexpbuilderphp)[aplus/pagination

Aplus Framework Pagination Library

2091.6M3](/packages/aplus-pagination)

PHPackages © 2026

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