kariricode/transformer
最新稳定版本:v1.1.0
Composer 安装命令:
composer require kariricode/transformer
包简介
A powerful and flexible data transformation component for PHP, part of the KaririCode Framework. It provides configurable processors for seamless manipulation and formatting of data attributes, offering a streamlined pipeline system for efficient data handling
关键字:
README 文档
README
A powerful and flexible data transformation component for PHP, part of the KaririCode Framework. It uses attribute-based transformation with configurable processors to ensure consistent data transformation and formatting in your applications.
Table of Contents
- Features
- Installation
- Usage
- Available Transformers
- Configuration
- Integration with Other KaririCode Components
- Development and Testing
- Contributing
- License
- Support and Community
Features
- Attribute-based transformation for object properties
- Comprehensive set of built-in transformers for common use cases
- Easy integration with other KaririCode components
- Configurable processors for customized transformation logic
- Extensible architecture allowing custom transformers
- Robust error handling and reporting
- Chainable transformation pipelines for complex data transformation
- Built-in support for multiple transformation scenarios
- Type-safe transformation with PHP 8.3 features
- Preservation of original data types
- Flexible formatting options for various data types
Installation
You can install the Transformer component via Composer:
composer require kariricode/transformer
Requirements
- PHP 8.3 or higher
- Composer
- Extensions:
ext-mbstring,ext-json
Usage
Basic Usage
- Define your data class with transformation attributes:
use KaririCode\Transformer\Attribute\Transform; class DataFormatter { #[Transform( processors: ['date' => ['inputFormat' => 'd/m/Y', 'outputFormat' => 'Y-m-d']] )] private string $date = '25/12/2024'; #[Transform( processors: ['number' => ['decimals' => 2, 'decimalPoint' => ',', 'thousandsSeparator' => '.']] )] private float $price = 1234.56; #[Transform( processors: ['mask' => ['type' => 'phone']] )] private string $phone = '11999887766'; // Getters and setters... }
- Set up the transformer and use it:
use KaririCode\ProcessorPipeline\ProcessorRegistry; use KaririCode\Transformer\Transformer; use KaririCode\Transformer\Processor\Data\{DateTransformer, NumberTransformer}; use KaririCode\Transformer\Processor\String\MaskTransformer; $registry = new ProcessorRegistry(); $registry->register('transformer', 'date', new DateTransformer()); $registry->register('transformer', 'number', new NumberTransformer()); $registry->register('transformer', 'mask', new MaskTransformer()); $transformer = new Transformer($registry); $formatter = new DataFormatter(); $result = $transformer->transform($formatter); if ($result->isValid()) { echo "Date: " . $formatter->getDate() . "\n"; // Output: 2024-12-25 echo "Price: " . $formatter->getPrice() . "\n"; // Output: 1.234,56 echo "Phone: " . $formatter->getPhone() . "\n"; // Output: (11) 99988-7766 }
Advanced Usage: Data Formatting
Here's an example of how to use the KaririCode Transformer in a real-world scenario, demonstrating various transformation capabilities:
use KaririCode\Transformer\Attribute\Transform; class ComplexDataTransformer { #[Transform( processors: ['case' => ['case' => 'snake']] )] private string $text = 'transformThisTextToSnakeCase'; #[Transform( processors: ['slug' => []] )] private string $title = 'This is a Title for URL!'; #[Transform( processors: ['arrayKey' => ['case' => 'camel']] )] private array $data = [ 'user_name' => 'John Doe', 'email_address' => 'john@example.com', 'phone_number' => '1234567890' ]; #[Transform( processors: [ 'template' => [ 'template' => 'Hello {{name}}, your order #{{order_id}} is {{status}}', 'removeUnmatchedTags' => true, 'preserveData' => true ] ] )] private array $templateData = [ 'name' => 'John', 'order_id' => '12345', 'status' => 'completed' ]; // Getters and setters... }
Available Transformers
String Transformers
-
CaseTransformer: Transforms string case (camel, snake, pascal, kebab).
- Configuration Options:
case: Target case format (lower, upper, title, sentence, camel, pascal, snake, kebab)preserveNumbers: Whether to preserve numbers in transformation
- Configuration Options:
-
MaskTransformer: Applies masks to strings (phone, CPF, CNPJ, etc.).
- Configuration Options:
mask: Custom mask patterntype: Predefined mask typeplaceholder: Mask placeholder character
- Configuration Options:
-
SlugTransformer: Generates URL-friendly slugs.
- Configuration Options:
separator: Separator characterlowercase: Convert to lowercasereplacements: Custom character replacements
- Configuration Options:
-
TemplateTransformer: Processes templates with variable substitution.
- Configuration Options:
template: Template stringremoveUnmatchedTags: Remove unmatched placeholderspreserveData: Keep original data in result
- Configuration Options:
Data Transformers
-
DateTransformer: Converts between date formats.
- Configuration Options:
inputFormat: Input date formatoutputFormat: Output date formatinputTimezone: Input timezoneoutputTimezone: Output timezone
- Configuration Options:
-
NumberTransformer: Formats numbers with locale-specific settings.
- Configuration Options:
decimals: Number of decimal placesdecimalPoint: Decimal separatorthousandsSeparator: Thousands separatorroundUp: Round up decimals
- Configuration Options:
-
JsonTransformer: Handles JSON encoding/decoding.
- Configuration Options:
encodeOptions: JSON encoding optionspreserveType: Keep original data typeassoc: Use associative arrays
- Configuration Options:
Array Transformers
-
ArrayFlattenTransformer: Flattens nested arrays.
- Configuration Options:
depth: Maximum depth to flattenseparator: Key separator for flattened structure
- Configuration Options:
-
ArrayGroupTransformer: Groups array elements by key.
- Configuration Options:
groupBy: Key to group bypreserveKeys: Maintain original keys
- Configuration Options:
-
ArrayKeyTransformer: Transforms array keys.
- Configuration Options:
case: Target case for keysrecursive: Apply to nested arrays
- Configuration Options:
-
ArrayMapTransformer: Maps array keys to new structure.
- Configuration Options:
mapping: Key mapping configurationremoveUnmapped: Remove unmapped keysrecursive: Apply to nested arrays
- Configuration Options:
Composite Transformers
-
ChainTransformer: Executes multiple transformers in sequence.
- Configuration Options:
transformers: Array of transformers to executestopOnError: Stop chain on first error
- Configuration Options:
-
ConditionalTransformer: Applies transformations based on conditions.
- Configuration Options:
condition: Condition callbacktransformer: Transformer to applydefaultValue: Value when condition fails
- Configuration Options:
Configuration
Transformers can be configured globally or per-instance. Example of configuring the NumberTransformer:
use KaririCode\Transformer\Processor\Data\NumberTransformer; $numberTransformer = new NumberTransformer(); $numberTransformer->configure([ 'decimals' => 2, 'decimalPoint' => ',', 'thousandsSeparator' => '.', ]); $registry->register('transformer', 'number', $numberTransformer);
Integration with Other KaririCode Components
The Transformer component integrates with:
- KaririCode\Contract: Provides interfaces for component integration
- KaririCode\ProcessorPipeline: Used for transformation pipelines
- KaririCode\PropertyInspector: Processes transformation attributes
Registry Example
Complete registry setup example:
$registry = new ProcessorRegistry(); // Register String Transformers $registry->register('transformer', 'case', new CaseTransformer()) ->register('transformer', 'mask', new MaskTransformer()) ->register('transformer', 'slug', new SlugTransformer()) ->register('transformer', 'template', new TemplateTransformer()); // Register Data Transformers $registry->register('transformer', 'date', new DateTransformer()) ->register('transformer', 'number', new NumberTransformer()) ->register('transformer', 'json', new JsonTransformer()); // Register Array Transformers $registry->register('transformer', 'arrayFlat', new ArrayFlattenTransformer()) ->register('transformer', 'arrayGroup', new ArrayGroupTransformer()) ->register('transformer', 'arrayKey', new ArrayKeyTransformer()) ->register('transformer', 'arrayMap', new ArrayMapTransformer());
Development and Testing
Similar development setup as the Validator component, using Docker and Make commands.
Available Make Commands
make up: Start servicesmake down: Stop servicesmake test: Run testsmake coverage: Generate coverage reportmake cs-fix: Fix code stylemake quality: Run quality checks
Contributing
Contributions are welcome! Please see our Contributing Guide.
License
MIT License - see LICENSE file.
Support and Community
- Documentation: https://kariricode.org/docs/transformer
- Issues: GitHub Issues
- Forum: KaririCode Club Community
- Stack Overflow: Tag with
kariricode-transformer
Built with ❤️ by the KaririCode team. Transforming data with elegance and precision.
统计信息
- 总下载量: 3
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 0
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2024-10-26