A fluent casting library for PHP.

dev-main 2025-04-09 03:54 UTC

This package is auto-updated.

Last update: 2025-04-09 03:57:19 UTC


README

A fluent, chainable transformation and validation utility for Laravel applications. Tx makes it easy to transform, cast, and validate values in your Laravel applications, with built-in support for dates and money transformations.

Installation

You can install the package via composer:

composer require alexthekiwi/tx

Then publish the configuration file:

php artisan vendor:publish --provider="Alexthekiwi\Tx\TxServiceProvider" --tag="config"

Features

  • Fluent, chainable API
  • Strong type conversions
  • Date transformations using Carbon
  • Money/Price transformations using brick/money
  • Fallbacks and error handling
  • Extensible with custom transformers

Usage

Basic Usage

use function Alexthekiwi\Tx\tx;

// Basic type conversions
$intValue = tx('42')->toInt(); // 42
$floatValue = tx('3.14')->toFloat(); // 3.14
$boolValue = tx(1)->toBool(); // true

Working with Dates

// Parse a date
$date = tx('2023-01-15')->toDate(); // Returns Carbon instance

// Parse a date with a specific format
$date = tx('15/01/2023')->fromFormat('d/m/Y')->toDate();

// Chain Carbon methods
$formattedDate = tx('2023-01-15')->toDate()->format('F j, Y'); // January 15, 2023
$nextMonth = tx('2023-01-15')->toDate()->addMonth()->format('Y-m-d'); // 2023-02-15

Working with Money

// Create a Money instance from a numeric value
$money = tx(100)->toPrice(); // $100 USD

// Format money values
$formattedPrice = tx(100)->toPrice()->getAmount(); // "100.00"

// Format with currency
$formattedWithCurrency = tx(100)->toPrice()->formatTo('en_US'); // "$100.00"

// Perform calculations
$discountedPrice = tx(100)->toPrice()->multipliedBy('0.9'); // $90 USD

Error Handling

// Using fallbacks
$safeInt = tx('not-a-number')->fallback(0)->toInt(); // 0

// Throwing exceptions
try {
    $value = tx('not-a-number')->throw()->toInt();
} catch (\Alexthekiwi\Tx\Exceptions\CannotTxException $e) {
    // Handle exception
}

// Using custom error handling
$customHandled = tx('not-a-number')
    ->failed(function($exception, $originalValue) {
        // Log the error
        Log::error("Failed to cast value: {$originalValue}", [
            'exception' => $exception,
        ]);
        
        return 0; // Return a default value
    })
    ->toInt();

Advanced Usage

// Chaining multiple transformations
$result = tx('{"date": "2023-01-15", "amount": 100}')
    ->toCollection()
    ->map(function ($item, $key) {
        if ($key === 'date') {
            return tx($item)->toDate();
        }
        
        if ($key === 'amount') {
            return tx($item)->toPrice();
        }
        
        return $item;
    });

// Custom transformers
$result = tx($value)
    ->using(new MyCustomTransformer())
    ->toCustomFormat();

Configuration

You can customize the default behavior by modifying the config/tx.php file:

return [
    // Default currency for money transformations
    'currency' => env('TX_DEFAULT_CURRENCY', 'USD'),
    
    'casters' => [
        'date' => [
            'class' => \Alexthekiwi\Tx\Transformers\TxCarbon::class,
            'default_format' => 'Y-m-d H:i:s',
        ],
        'price' => [
            'class' => \Alexthekiwi\Tx\Transformers\TxBrickMoney::class,
        ],
    ],
];

Extending Tx

You can create your own transformers by implementing the appropriate interface:

use Alexthekiwi\Tx\Contracts\TxDateContract;
use Carbon\Carbon;

class MyCustomDateTransformer implements TxDateContract
{
    public function toDate(mixed $value, ?string $format = null): ?Carbon
    {
        // Custom implementation
    }
}

Then update your config to use your custom transformer:

'casters' => [
    'date' => [
        'class' => \App\Transformers\MyCustomDateTransformer::class,
    ],
],

License

The MIT License (MIT). Please see License File for more information.