PHP code example of sirix / redaction

1. Go to this page and download the library: Download sirix/redaction library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sirix / redaction example snippets


use Sirix\Redaction\Redactor;
use Sirix\Redaction\RedactorOptions;
use Sirix\Redaction\Rule\StartEndRule;
use Sirix\Redaction\Rule\EmailRule;
use Sirix\Redaction\Rule\Factory\SharedRuleFactory;
use Sirix\Redaction\Rule\NameRule;
use Sirix\Redaction\Enum\ObjectViewModeEnum;

$redactor = new Redactor(
    customRules: [
        // Overwrite or add rules per key; custom rules override defaults when keys overlap
        // Option 1 — direct instantiation:
        'card_number' => new StartEndRule(6, 4),
        // Option 2 — via factory helper (equivalent):
        // 'card_number' => SharedRuleFactory::startEnd(6, 4),
        'email' => new EmailRule(),
        // Factory helper (equivalent):
        // 'email' => SharedRuleFactory::email(),
        'name'  => new NameRule(),
        // Factory helper (equivalent):
        // 'name' => SharedRuleFactory::name(),

        // Regex key matchers are ordered list entries. They match keys, while the
        // nested rule still controls how the scalar value is masked.
        SharedRuleFactory::regexKey(
            '/password|passwd|secret|token|api[_-]?key|authorization|cookie/i',
            SharedRuleFactory::fixedValue('[Filtered]'),
        ),
    ],
    options: new RedactorOptions(
        objectViewMode: ObjectViewModeEnum::Copy,
        maxDepth: 8,
        maxItemsPerContainer: 100,
        maxTotalNodes: 5000,
    ),
);

// Rule precedence is: custom exact key, custom regex matcher in configured order, then defaults.
// Note: By default, Redactor loads a set of sensible default rules.
// To disable them and use only your own custom rules, pass useDefaultRules: false
// e.g. $redactor = new Redactor(customRules: [...], useDefaultRules: false);

// Optional tuning can also be done fluently.
// Redactor is immutable in 2.0: with* methods return a configured copy.
// Always assign the returned instance.
$redactor = $redactor
    ->withReplacement('*')                 // character used to build masks
    ->withTemplate('%s')                   // safe sprintf template with exactly one plain %s
    ->withLengthLimit(null)                // max length of the resulting masked value in bytes (null = unlimited)
    ->withObjectViewMode(ObjectViewModeEnum::Copy) // Copy | PublicArray | Skip
    ->withMaxDepth(null)                   // limit recursion depth for arrays/objects (null = unlimited)
    ->withMaxItemsPerContainer(null)       // limit items per array/object (null = unlimited)
    ->withMaxTotalNodes(null)              // global cap on visited nodes (null = unlimited)
    ->withOnLimitExceededCallback(function (array $info): void {
        // Called when a limit is hit or a cycle is detected; inspect $info if desired
        // e.g., error_log('Redaction limit: '.json_encode($info));
    })
    ->withOverflowPlaceholder('...');      // default is '...', pass null to omit overflow markers

$payload = [
    'card_number' => '1234567890123456',
    'user' => [
        'email' => '[email protected]',
        'name'  => 'John Doe',
        'phone' => '+44123456789012',
    ],
];

$redacted = $redactor->redact($payload);

use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Sirix\Redaction\Redactor;
use Sirix\Redaction\Bridge\Monolog\RedactorProcessor;

$logger = new Logger('app');
$logger->pushHandler(new StreamHandler('php://stdout'));

$redactor = new Redactor(); // you may pass custom rules here as in the core example
$processor = new RedactorProcessor($redactor);
$logger->pushProcessor($processor);

$logger->info('User checkout', [
    'card_number' => '1234567890123456',
    'user' => [
        'email' => '[email protected]',
        'name'  => 'John Doe',
        'phone' => '+44123456789012',
    ],
]);

// config/config.php or a module config
return [
    'dependencies' => [
        // You can omit this if you use the provided ConfigProvider
        'aliases' => [
            Sirix\Redaction\RedactorInterface::class => Sirix\Redaction\Redactor::class,
        ],
        'factories' => [
            Sirix\Redaction\Redactor::class => Sirix\Redaction\Factory\RedactorFactory::class,
        ],
    ],

    // Redactor configuration
    'redactor' => [
        'options' => [
            // Custom rules (same structure as passing to the constructor)
            'rules' => [
                'card_number' => new Sirix\Redaction\Rule\StartEndRule(6, 4),
                Sirix\Redaction\Rule\Factory\SharedRuleFactory::regexKey(
                    '/password|passwd|secret|token|api[_-]?key|authorization|cookie/i',
                    Sirix\Redaction\Rule\Factory\SharedRuleFactory::fixedValue('[Filtered]'),
                ),
            ],

            // Whether to load built‑in default rules (bool, default: true)
            'use_default_rules' => true,

            // Core options (all optional, read strictly; no scalar coercion)
            'replacement' => '*',                 // string
            'template' => '%s',                   // string, exactly one plain %s placeholder
            'length_limit' => null,               // int|null, numeric strings are invalid
            'object_view_mode' => 'copy',         // enum instance or: copy|public_array|skip
            'max_depth' => null,                  // int|null, numeric strings are invalid
            'max_items_per_container' => null,    // int|null, numeric strings are invalid
            'max_total_nodes' => null,            // int|null, numeric strings are invalid
            'on_limit_exceeded_callback' => null, // callable|null
            'overflow_placeholder' => '...',      // string|null, default: '...'
        ],
    ],
];

use Sirix\Redaction\RedactorInterface;

final class MyService
{
    public function __construct(private RedactorInterface $redactor) {}
}

$redactor = $redactor
    ->withMaxDepth(8)
    ->withMaxItemsPerContainer(100)
    ->withMaxTotalNodes(5000)
    ->withOverflowPlaceholder('...');

$redactor = new Redactor(customRules: [], useDefaultRules: false);

use Sirix\Redaction\Rule\Factory\SharedRuleFactory;
use Sirix\Redaction\Redactor;

$redactor = new Redactor([
    'card_number' => SharedRuleFactory::startEnd(6, 4),
    'email'       => SharedRuleFactory::email(),
    'phone'       => SharedRuleFactory::phone(),
]);

SharedRuleFactory::regexKey(
    '/password|passwd|secret|token|api[_-]?key|authorization|cookie/i',
    SharedRuleFactory::fixedValue('[Filtered]'),
);

use Sirix\Redaction\RedactionRuleContextInterface;
use Sirix\Redaction\Rule\RedactionRuleInterface;

use function str_repeat;

final class MyRule implements RedactionRuleInterface
{
    public function apply(string $value, RedactionRuleContextInterface $context): ?string
    {
        if ('' === $value) {
            return null;
        }

        return str_repeat($context->getReplacement(), 3);
    }
}

use Sirix\Redaction\Enum\ObjectViewModeEnum;
use Sirix\Redaction\Redactor;
use Sirix\Redaction\RedactorOptions;

$redactor = new Redactor(
    options: new RedactorOptions(
        replacement: '*',
        template: '%s',
        objectViewMode: ObjectViewModeEnum::Copy,
        maxDepth: 8,
        maxItemsPerContainer: 100,
        maxTotalNodes: 5000,
        overflowPlaceholder: '...',
    ),
);

use Sirix\Redaction\Rule\UnicodeStartEndRule;

$redactor = new Redactor([
    'display_name' => new UnicodeStartEndRule(2, 2),
]);