PHPackages                             logcomex/php-utils - 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. logcomex/php-utils

ActiveLibrary

logcomex/php-utils
==================

PHP Utils for Lumen and Laravel projects

2.0.1(3y ago)1219.9k—0%1[2 PRs](https://github.com/comexio/php-utils/pulls)1MITPHPPHP ^7.4 || ^8.1

Since Jun 9Pushed 10mo ago4 watchersCompare

[ Source](https://github.com/comexio/php-utils)[ Packagist](https://packagist.org/packages/logcomex/php-utils)[ RSS](/packages/logcomex-php-utils/feed)WikiDiscussions master Synced 1mo ago

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

php-utils
=========

[](#php-utils)

PHP Utilities for Laravel/Lumen

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

[](#installation)

```
cd /path/to/your/project
composer require logcomex/php-utils
```

Utilities Packages
------------------

[](#utilities-packages)

- Contracts
- Exceptions
- Functionalities
- Handlers
- Helpers
- Loggers
- Logs
- Middlewares
- Providers
- Singletons

Contracts
---------

[](#contracts)

> Have all the contracts (interfaces) used by the php-utils classes and other that you can use in your project.

Exceptions
----------

[](#exceptions)

> Have all the exceptions used by the php-utils classes. And others that you can use in your project to segregate your errors types .

#### ApiException

[](#apiexception)

> You can use for all exceptions in 400 range http code

```
ApiException(string $token,
			string $message,
			int $httpCode = Response::HTTP_BAD_REQUEST,
			Exception $previous = null)
```

VisibilityFunctionReturn TypepublicgetHttpCodeintpublicgetTokenstringpublic\_\_toStringstringpublictoArrayarraypublictoJsonstring#### BadImplementationException

[](#badimplementationexception)

> This exception means that a situation has been overlooked or incorrectly done by the developer.

```
BadImplementationException(string $token,
            string $message,
			int $httpCode = Response::HTTP_INTERNAL_SERVER_ERROR,
			Exception $previous = null)
```

VisibilityFunctionReturn TypepublicgetHttpCodeintpublicgetTokenstringpublic\_\_toStringstringpublictoArrayarraypublictoJsonstring#### SecurityException

[](#securityexception)

> This exception serves to point out some security problem in your application.

```
SecurityException(string $token,
			string $message,
			int $httpCode = Response::HTTP_FORBIDDEN,
			Exception $previous = null)
```

VisibilityFunctionReturn TypepublicgetHttpCodeintpublicgetTokenstringpublic\_\_toStringstringpublictoArrayarraypublictoJsonstring#### UnavailableServiceException

[](#unavailableserviceexception)

> This exception serves to point out that your or other application is unavailable.

```
UnavailableServiceException(string $token,
			string $message,
			int $httpCode = Response::HTTP_FORBIDDEN,
			Exception $previous = null)
```

VisibilityFunctionReturn TypepublicgetHttpCodeintpublicgetTokenstringpublicgetServicestringpublic\_\_toStringstringpublictoArrayarraypublictoJsonstringFunctionalities
---------------

[](#functionalities)

> They're a pack of traits that can be useful in your code

#### PropertiesExporterFunctionality

[](#propertiesexporterfunctionality)

> You can use this functionality to export an array with you class properties

```
public static function properties(): array
```

#### PropertiesAttacherFunctionality

[](#propertiesattacherfunctionality)

> You can use this functionality to attach in your class properties the values passed in the parameter.
>
> > **Note:** To uses this functionality, you need use the PropertiesExporterFunctionality in the class.

```
public function attachValues(array $values): void
```

ExceptionReasonBadImplementationExceptionWhen you don't use PropertiesExporterFunctionality#### ValuesExporterToArrayFunctionality

[](#valuesexportertoarrayfunctionality)

> You can use this functionality to easily get all the properties of class in an array.
>
> > **Note:** To uses this functionality, you need to do two things:
> >
> > 1. The class must implement Illuminate\\Contracts\\Support\\Arrayable.
> > 2. The class must use PropertiesExporterFunctionality.

```
public function toArray()
```

ExceptionReasonBadImplementationExceptionWhen yout don't implement the the Arrayable contractBadImplementationExceptionWhen you don't use PropertiesExporterFunctionality#### ValuesExporterToJsonFunctionality

[](#valuesexportertojsonfunctionality)

> You can use this functionality to easily get all the properties of class in a Json.
>
> > **Note:** To uses this functionality, you need to do two things:
> >
> > 1. The class must implement Illuminate\\Contracts\\Support\\Jsonable.
> > 2. The class must use PropertiesExporterFunctionality.

```
public function toJson()
```

ExceptionReasonBadImplementationExceptionWhen yout don't implement the the Jsonable contractBadImplementationExceptionWhen you don't use PropertiesExporterFunctionalityHelpers
-------

[](#helpers)

> They're a pack of Helpers classes and traits.

#### EnumHelper

[](#enumhelper)

> It's a trait that provide some utilities to your Enumerators classes.

VisibilityFunctionReturn TypePurposepublicallarrayGet all the constants of your Enumerator```
use Logcomex\PhpUtils\Helpers\EnumHelper;

class ProductEnum
{
	user EnumHelper;
	public const EXAMPLE = 'example';
	public const EXAMPLE2 = 'example2';
}

$allProducts = ProductEnum::all();
```

Loggers
-------

[](#loggers)

> The idea of this package is provide all the Loggers classes.

### LogcomexLogger

[](#logcomexlogger)

> Using this class you can easily provide a log template, that is very important to integrate with Datadog.

```
// bootstrap/app.php

$app->register(Logcomex\PhpUtils\Providers\LogcomexLoggerProvider::class);

$app->withFacades(true, [
    Logcomex\PhpUtils\Facades\Logger::class => 'Logger',
]);

Logger::info('TOKEN-001', ['reason' => 'test',]);
```

Middlewares
-----------

[](#middlewares)

> They're a pack of Middleware classes.

#### AuthenticateMiddleware

[](#authenticatemiddleware)

> It is a class that provides authentication verification. You'll need a AuthProvider configured in your application to use this Middleware.

```
// bootstrap/app.php
$app->register(Your\Provider\AuthServiceProvider::class);

// Using in global mode
$app->middleware([
    Logcomex\PhpUtils\Middlewares\AuthenticateMiddleware::class,
]);

// Or, by specific route
$app->routeMiddleware([
    'auth' => Logcomex\PhpUtils\Middlewares\AuthenticateMiddleware::class,
]);
```

#### RequestLogMiddleware

[](#requestlogmiddleware)

> It is a class that provides a log for each request in your api. You can choose what you gonna print in the log, such as: request-header, request-server, request-payload, response-header, response-content, response-time, and trace-id.
>
>  The .env configuration:

Env VariableTypeDescriptionREQUEST\_LOGGER\_ENABLE\_REQUEST\_HEADERbooleanPrint in the log, the request header informationREQUEST\_LOGGER\_ENABLE\_REQUEST\_SERVERbooleanPrint in the log, the request server informationREQUEST\_LOGGER\_ENABLE\_REQUEST\_PAYLOADbooleanPrint in the log, the request payload informationREQUEST\_LOGGER\_ENABLE\_RESPONSE\_HEADERbooleanPrint in the log, the response header informationREQUEST\_LOGGER\_ENABLE\_RESPONSE\_CONTENTbooleanPrint in the log, the response content informationREQUEST\_LOGGER\_ENABLE\_RESPONSE\_TIMEbooleanPrint in the log, the response execution time informationREQUEST\_LOGGER\_ALLOWED\_DATA\_REQUEST\_SERVERstringIf has data in this variable, the middleware gonna print just the infos requested in this setting```
// config/requestLog.php
return [
    'enable-request-header' => env('REQUEST_LOGGER_ENABLE_REQUEST_HEADER', true),
    'enable-request-server' => env('REQUEST_LOGGER_ENABLE_REQUEST_SERVER', true),
    'enable-request-payload' => env('REQUEST_LOGGER_ENABLE_REQUEST_PAYLOAD', true),
    'enable-response-header' => env('REQUEST_LOGGER_ENABLE_RESPONSE_HEADER', true),
    'enable-response-content' => env('REQUEST_LOGGER_ENABLE_RESPONSE_CONTENT', true),
    'enable-response-time' => env('REQUEST_LOGGER_ENABLE_RESPONSE_TIME', true),
    'allowed-data-request-server' => explode(';', env('REQUEST_LOGGER_ALLOWED_DATA_REQUEST_SERVER', '')),
];

// bootstrap/app.php
$app->configure('requestLog');

// Using in global mode
$app->middleware([
    Logcomex\PhpUtils\Middlewares\TracerMiddleware::class, // If you gonna use tracer, it must be above the requestlog
    Logcomex\PhpUtils\Middlewares\RequestLogMiddleware::class, // And after trace, you need the request log
]);
```

#### ResponseTimeLogMiddleware

[](#responsetimelogmiddleware)

> It is a class that registers the response time of each request in your api. You can choose what request will be measured through calling the middleware by route.

First of all, you have to define the framework start time globally before requiring anything in your bootstrap:

```
// bootstrap/app.php
if (!defined('GLOBAL_FRAMEWORK_START')) {
    define('GLOBAL_FRAMEWORK_START', microtime(true));
}
```

Configuration:

> Your app config has to contain the key 'api-name', which will be used by this middleware for identifying what API the response time belongs to.

```
// bootstrap/app.php
$app->configure('app');
```

Usage:

> It is IMPORTANT that you call this middleware as the first one, so the response time calc can be the most accurate as possible.

```
// Using in global mode
$app->middleware([
    Logcomex\PhpUtils\Middlewares\ResponseTimeLogMiddleware::class,
]);

// Using in specific routes
$app->routeMiddleware([
    'response-time-log' => Logcomex\PhpUtils\Middlewares\ResponseTimeLogMiddleware::class,
]);
Route::group(
    [
        'prefix' => 'example',
        'middleware' => ['response-time-log'],
    ],
    function () {
        Route::get('responseTimeLog', 'ExampleClassName@exampleMethodName');
    });
```

#### TracerMiddleware

[](#tracermiddleware)

> It is a class that provides tracer functionality for your api. So your log can use this value and the HttpHelper. You must create a tracer config file in config folder. We recommend uses this middleware as global, and the first one in middlewares chain.

```
// config/tracer.php
return [
    'headersToPropagate' => explode(';', env('TRACER_HEADERS_TO_PROPAGATE')),
];

// bootstrap/app.php
$app->configure('tracer');

// Using in global mode
$app->middleware([
    Logcomex\PhpUtils\Middlewares\TracerMiddleware::class,
    // the other middlewares
]);

// Or, by specific route
$app->routeMiddleware([
    'tracer' => Logcomex\PhpUtils\Middlewares\TracerMiddleware::class,
]);
```

#### AccreditedApiKeysMiddleware

[](#accreditedapikeysmiddleware)

> It is a class that provides a first level of security for your api. The best analogy is that middleware is your "API guest list".
>
> You need to register a configuration file called accreditedApiKeys, with all the api-keys that can request your api.
>
> Therefore, if the request does not contain the x-infra-key header or a allowed value, the API denies the request with the security exception.
>
> It is recommended to use as a global middleware, and if you need to avoid this middleware for some routes, just insert into the public route group.

```
// config/accreditedApiKeys.php
return [
    'api-1' => env('API_1_X_API_KEY'),
    'api-2' => env('API_2_X_API_KEY'),
    'api-3' => env('API_3_X_API_KEY'),
];

// bootstrap/app.php
$app->configure('accreditedApiKeys');

// Using in global mode
$app->middleware([
    Logcomex\PhpUtils\Middlewares\AccreditedApiKeysMiddleware::class,
]);

// routes/api.php
$router->group(['prefix' => 'public',], function () use ($router) {
    $router->get('test', 'Controller@test');// this route does not need x-infra-key validation
});
```

Providers
---------

[](#providers)

> The idea of this package is provide some providers. For a better understanding: [Lumen Providers](https://lumen.laravel.com/docs/6.x/providers)

### LogcomexLoggerProvider

[](#logcomexloggerprovider)

> You have to use this provider when you're using the Logger Facade.

```
// bootstrap/app.php

$app->register(Logcomex\MicroservicesCore\Providers\LogcomexLoggerProvider::class);

## Singletons

> They're a pack of Singleton classes.

#### TracerSingleton

> It is a class that provides the tracer value.

## Unit Tests Coverage

Master
[![codecov](https://codecov.io/gh/comexio/php-utils/branch/master/graph/badge.svg)](https://codecov.io/gh/comexio/php-utils)

## TODO

 - [ ] HttpHelper Doc
 - [ ] TokenHelper Doc
 - [ ] Handlers Package Doc
	 - [ ] ExceptionHandler Doc
 - [ ] Logs Package Doc
	 - [ ] RequestLog Doc
 - [ ] Middlewares Package Doc
	 - [ ] AllowedHostsMiddleware Doc
	 - [ ] CorsMiddleware Doc

## Contributing

- Open an issue first to discuss potential changes/additions.
- Open a pull request, you need two approvals and tests need to pass Travis CI.
```

###  Health Score

48

—

FairBetter than 95% of packages

Maintenance39

Infrequent updates — may be unmaintained

Popularity35

Limited adoption so far

Community23

Small or concentrated contributor base

Maturity81

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 69.6% 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 ~19 days

Recently: every ~75 days

Total

57

Last Release

1014d ago

Major Versions

0.11.4 → 1.5.52021-08-06

0.11.5 → 1.5.62021-09-02

0.11.7 → 1.5.72021-12-15

0.12.1 → 2.0.02022-10-03

0.12.4 → 2.x-dev2022-10-26

PHP version history (4 changes)0.0.1PHP ^7.2

1.0.0PHP ^8.0

2.0.0PHP ^8.1

2.0.1PHP ^7.4 || ^8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/af066ecbb915e1430d01d96b053b90a205c749cb3e99b943334e0684049b28c1?d=identicon)[logcomex](/maintainers/logcomex)

---

Top Contributors

[![crysglodzienski](https://avatars.githubusercontent.com/u/38006098?v=4)](https://github.com/crysglodzienski "crysglodzienski (158 commits)")[![gabriel-ward](https://avatars.githubusercontent.com/u/79272334?v=4)](https://github.com/gabriel-ward "gabriel-ward (11 commits)")[![gustavoraamos](https://avatars.githubusercontent.com/u/72817476?v=4)](https://github.com/gustavoraamos "gustavoraamos (11 commits)")[![Vit0rDuarte](https://avatars.githubusercontent.com/u/85963519?v=4)](https://github.com/Vit0rDuarte "Vit0rDuarte (9 commits)")[![djunior-logcomex](https://avatars.githubusercontent.com/u/73896466?v=4)](https://github.com/djunior-logcomex "djunior-logcomex (7 commits)")[![AndreFontouraLogComex](https://avatars.githubusercontent.com/u/171580937?v=4)](https://github.com/AndreFontouraLogComex "AndreFontouraLogComex (6 commits)")[![nuneseth](https://avatars.githubusercontent.com/u/66334239?v=4)](https://github.com/nuneseth "nuneseth (5 commits)")[![amadeologcomex](https://avatars.githubusercontent.com/u/32842489?v=4)](https://github.com/amadeologcomex "amadeologcomex (3 commits)")[![marlondamaral](https://avatars.githubusercontent.com/u/87086788?v=4)](https://github.com/marlondamaral "marlondamaral (3 commits)")[![fmessercosta](https://avatars.githubusercontent.com/u/75991804?v=4)](https://github.com/fmessercosta "fmessercosta (2 commits)")[![danilocolasso](https://avatars.githubusercontent.com/u/2896393?v=4)](https://github.com/danilocolasso "danilocolasso (2 commits)")[![AndreFontouraLC](https://avatars.githubusercontent.com/u/71645809?v=4)](https://github.com/AndreFontouraLC "AndreFontouraLC (2 commits)")[![brunologcomex2](https://avatars.githubusercontent.com/u/73964040?v=4)](https://github.com/brunologcomex2 "brunologcomex2 (2 commits)")[![pedrologcomex](https://avatars.githubusercontent.com/u/74609022?v=4)](https://github.com/pedrologcomex "pedrologcomex (2 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")[![robertosouza-logcomex](https://avatars.githubusercontent.com/u/148151946?v=4)](https://github.com/robertosouza-logcomex "robertosouza-logcomex (1 commits)")[![jorgelogcomex](https://avatars.githubusercontent.com/u/66333786?v=4)](https://github.com/jorgelogcomex "jorgelogcomex (1 commits)")[![dependabot-preview[bot]](https://avatars.githubusercontent.com/in/2141?v=4)](https://github.com/dependabot-preview[bot] "dependabot-preview[bot] (1 commits)")

---

Tags

hacktoberfestlumenphp

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/logcomex-php-utils/health.svg)

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

###  Alternatives

[neuron-core/neuron-ai

The PHP Agentic Framework.

1.8k245.3k21](/packages/neuron-core-neuron-ai)[tencentcloud/tencentcloud-sdk-php

TencentCloudApi php sdk

3731.2M42](/packages/tencentcloud-tencentcloud-sdk-php)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)

PHPackages © 2026

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