Oihana PHP

compress.php

Table of Contents

Functions

compress()  : object
Compress the given object by removing properties that match certain conditions.

Functions

compress()

Compress the given object by removing properties that match certain conditions.

compress(object $object[, array{conditions?: callable|callable[], depth?: null|int, excludes?: string[], recursive?: bool, removeKeys?: string[], throwable?: bool} $options = [] ][, int $currentDepth = 0 ]) : object

This function traverses the object and removes properties according to the provided options. It can operate recursively on nested objects and arrays.

Parameters
$object : object

The object to compress.

$options : array{conditions?: callable|callable[], depth?: null|int, excludes?: string[], recursive?: bool, removeKeys?: string[], throwable?: bool} = []

Optional configuration.

$currentDepth : int = 0

Internal counter used to track recursion depth.

Tags
throws
InvalidArgumentException

If invalid callbacks are provided and 'throwable' is true.

example

Basic removal of null values

use function oihana\core\objects\compress;

$obj = (object)[
    'id'          => 1,
    'name'        => 'hello',
    'description' => null,
];

$result = compress($obj, [
    'conditions' => fn($v) => $v === null,
]);

// Result: { "id":1, "name":"hello" }
echo json_encode($result);
example

Excluding certain properties

$obj = (object)[
    'id'    => 1,
    'debug' => 'keep me',
    'temp'  => null,
];

$result = compress($obj, [
    'conditions' => fn($v) => $v === null,
    'excludes'   => ['debug'],
]);

// Result: { "id":1, "debug":"keep me" }
echo json_encode($result);
example

Removing properties by name

$obj = (object)[
    'id'    => 1,
    'token' => 'secret',
    'name'  => 'test',
];

$result = compress($obj, [
    'removeKeys' => ['token'],
]);

// Result: { "id":1, "name":"test" }
echo json_encode($result);
example

Recursive compression

$obj = (object)[
    'id'    => 1,
    'child' => (object)[
        'value' => null,
        'label' => 'ok',
    ],
];

$result = compress($obj, [
    'conditions' => fn($v) => $v === null,
    'recursive'  => true,
]);

// Result: { "id":1, "child":{ "label":"ok" } }
echo json_encode($result);
author

Marc Alcaraz

since
1.0.0
Return values
object

The compressed object, with properties removed according to the rules.


        
On this page

Search results