PHP code example of nacosvel / transformer

1. Go to this page and download the library: Download nacosvel/transformer 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/ */

    

nacosvel / transformer example snippets


$originals = [
    'total_fee'           => 9900,
    'intent'              => 'CAPTURE',
    'purchase_units'      => [
        [
            'reference_id' => 'ORD20250520001',
            'amount'       => [
                'currency_code' => 'USD',
                'value'         => '99.00',
            ],
        ],
    ],
    'application_context' => [
        'return_url' => 'https://example.com/pay/return',
        'cancel_url' => 'https://example.com/pay/notify/paypal',
    ],
];

$targets = [];

$response = Converter::convert($originals, [
    $rule = new FieldMappingRule(
        'total_fee',
        'amount',
        fn($value) => $value / 100
    ),
    $rule = new NestedMappingRule(
        'purchase_units.0.amount.currency_code',
        'payment_code',
    ),
    $rule = new WildcardMapperRule([
        'purchase_units_amount'  => [
            'input'     => 'purchase_units.0.amount.value',
            'transform' => fn($v) => $v * 100,
        ],
        'purchase_units_amounts' => 'purchase_units.*.amount.value',
    ]),
], [
    'default_value' => '1234567890',
]);

use Nacosvel\Transformer\ConditionRule;

$rule = new ConditionRule(
    fn($originals, $targets) => isset($originals['total_fee']),
    function ($originals, $targets) {
        $targets['amount'] = $originals['total_fee'] / 100;
        return $targets;
    }
);

use Nacosvel\Transformer\DefaultValueRule;

$rule = new DefaultValueRule(
    'trade_type', 'JSAPI'
);

use Nacosvel\Transformer\FieldMappingRule;

$rule = new FieldMappingRule(
    'total_fee',
    'amount',
    fn($value) => $value / 100
);

use Nacosvel\Transformer\InvokeRule;

$rule = new InvokeRule(function ($originals, $targets) {
    return [
        'amount' => $originals['total_fee'] / 100,
    ];
});

use Nacosvel\Transformer\NestedMappingRule;

$rule = new NestedMappingRule(
    'purchase_units.0.amount.currency_code',
    'code',
);

use Nacosvel\Transformer\WildcardMapperRule;

$rule = new WildcardMapperRule([
    'amount'  => [
        'input'     => 'purchase_units.0.amount.value',
        'transform' => fn($v) => $v * 100,
    ],
    'amounts' => 'purchase_units.*.amount.value',
    'default' => [
        'input'     => null,
        'default'   => 'default value',
    ],
]);