Migration v1 to v2 - Grazulex/laravel-arc GitHub Wiki

🔄 Migration from v1 to v2

Overview

Laravel Arc v2.0 introduces significant improvements and new features while maintaining backward compatibility for most use cases. This guide helps you migrate from v1.x to v2.0.

What's New in v2.0

🆕 Major Features

  • Unified Property Attribute - Single #[Property()] attribute for all configurations
  • Transformation Pipeline System - Powerful data transformation capabilities
  • Auto-Discovery Relations - Automatic relationship detection and management
  • Smart Validation Generation - Enhanced validation rule generation
  • Debug & Analysis Tools - Built-in debugging and analysis features
  • Enhanced Type Safety - Improved PHP 8+ type system integration
  • Performance Optimizations - Better caching and memory management

🔧 Improvements

  • Better IDE support and autocompletion
  • More comprehensive error handling
  • Enhanced testing capabilities
  • Improved documentation and examples
  • Better Laravel 11 compatibility

Breaking Changes

While v2.0 maintains backward compatibility for most features, some changes may require updates to your code.

1. Namespace Changes

Old (v1.x):

use LaravelArc\Attributes\PropertyType;
use LaravelArc\Attributes\Required;
use LaravelArc\Attributes\Validation;

New (v2.0):

use Grazulex\LaravelArc\Attributes\Property;

2. Unified Property Attribute

Old (v1.x):

class User extends Model
{
    #[PropertyType('string')]
    #[Required(true)]
    #[Validation('min:2|max:100')]
    public string $name;

    #[PropertyType('email')]
    #[Required(true)]
    public string $email;
}

New (v2.0):

class User extends Model
{
    use HasArcProperties;

    #[Property(
        type: 'string',
        required: true,
        minLength: 2,
        maxLength: 100
    )]
    public string $name;

    #[Property(
        type: 'email',
        required: true
    )]
    public string $email;
}

3. Configuration File Changes

Old (v1.x):

// config/laravel-arc.php
return [
    'strict_mode' => false,
    'auto_validation' => true,
];

New (v2.0):

// config/laravel-arc.php
return [
    'auto_discovery' => [
        'enabled' => true,
        'cache_duration' => 3600,
    ],
    'validation' => [
        'auto_generate' => true,
        'strict_mode' => false,
    ],
    'debug' => [
        'enabled' => env('APP_DEBUG', false),
        'log_transformations' => false,
    ],
    'pipeline' => [
        'cache_results' => true,
        'parallel_processing' => false,
    ],
];

Step-by-Step Migration

Step 1: Update Dependencies

Update your composer.json:

{
    "require": {
        "grazulex/laravel-arc": "^2.0"
    }
}

Run the update:

composer update grazulex/laravel-arc

Step 2: Update Configuration

Publish the new configuration file:

php artisan vendor:publish --provider="Grazulex\LaravelArc\LaravelArcServiceProvider" --tag="config" --force

Review and adjust the new configuration options in config/laravel-arc.php.

Step 3: Update Model Attributes

Use the automated migration command (if available) or update manually:

# Automated migration (if implemented)
php artisan arc:migrate-attributes

# Or analyze your models first
php artisan arc:analyze --migration

Manual Migration Example:

// Before (v1.x)
class Product extends Model
{
    #[PropertyType('string')]
    #[Required(true)]
    #[Validation('min:3|max:200')]
    public string $title;

    #[PropertyType('float')]
    #[Required(true)]
    #[Validation('min:0.01|max:99999.99')]
    public float $price;

    #[PropertyType('enum')]
    #[EnumClass(ProductStatus::class)]
    public ProductStatus $status;
}

// After (v2.0)
class Product extends Model
{
    use HasArcProperties;

    #[Property(
        type: 'string',
        required: true,
        minLength: 3,
        maxLength: 200
    )]
    public string $title;

    #[Property(
        type: 'float',
        required: true,
        min: 0.01,
        max: 99999.99
    )]
    public float $price;

    #[Property(
        type: 'enum',
        enum: ProductStatus::class
    )]
    public ProductStatus $status;
}

Step 4: Update Custom Validation Rules

Old (v1.x):

#[Validation(['required', 'string', 'unique:users,email'])]
public string $email;

New (v2.0):

#[Property(
    type: 'email',
    required: true,
    rules: ['unique:users,email']
)]
public string $email;

Step 5: Update Method Calls

Some method signatures have changed:

Old (v1.x):

$rules = $model->getValidationRules();
$model->validateAttributes($data);

New (v2.0):

$rules = $model->getValidationRules();
$validator = $model->validateData($data);

Step 6: Test Your Application

Run your test suite to ensure everything works:

php artisan test

Migration Tools

Analysis Command

Use the analysis command to identify migration needs:

# Analyze all models
php artisan arc:analyze

# Analyze specific model
php artisan arc:analyze --model=User

# Get migration suggestions
php artisan arc:analyze --migration-hints

Migration Helper Script

Create a migration script to automate the process:

<?php
// migration_helper.php

require_once 'vendor/autoload.php';

class ArcMigrationHelper
{
    public function migrateModel(string $modelPath): void
    {
        $content = file_get_contents($modelPath);
        
        // Replace old attributes with new Property attribute
        $patterns = [
            // PropertyType + Required + Validation -> Property
            '/\#\[PropertyType\(([^)]+)\)\]\s*\#\[Required\(([^)]+)\)\]\s*\#\[Validation\(([^)]+)\)\]/' => 
                '#[Property(type: $1, required: $2, rules: $3)]',
            
            // Add HasArcProperties trait
            '/(class\s+\w+\s+extends\s+Model\s*\{)/' => 
                '$1\n    use HasArcProperties;\n',
        ];
        
        $content = preg_replace(array_keys($patterns), array_values($patterns), $content);
        
        file_put_contents($modelPath, $content);
    }
    
    public function migrateDirectory(string $path): void
    {
        $files = glob($path . '/*.php');
        
        foreach ($files as $file) {
            if (str_contains(file_get_contents($file), 'PropertyType')) {
                $this->migrateModel($file);
                echo "Migrated: {$file}\n";
            }
        }
    }
}

// Usage
$helper = new ArcMigrationHelper();
$helper->migrateDirectory('app/Models');

Feature Mapping

Attribute Mapping

v1.x Attributes v2.0 Property Parameter
PropertyType('string') type: 'string'
Required(true) required: true
Validation('min:5') minLength: 5 or rules: ['min:5']
Default('value') default: 'value'
EnumClass(Status::class) enum: Status::class
CustomCast(Money::class) cast: Money::class

Method Mapping

v1.x Methods v2.0 Methods
getValidationRules() getValidationRules()
validateAttributes($data) validateData($data)
getAttributeDefinition($name) getArcProperty($name)
setAttributeValue($name, $value) setArcProperty($name, $value)

New Features in v2.0

1. Transformation Pipeline

Add data transformations to your properties:

#[Property(
    type: 'string',
    transform: 'trim|lowercase|ucfirst',
    maxLength: 100
)]
public string $name;

#[Property(
    type: 'float',
    transform: 'round:2',
    min: 0.01
)]
public float $price;

2. Auto-Discovery Relations

Let Arc automatically discover and manage relationships:

class User extends Model
{
    use HasArcProperties;

    #[Property(
        type: 'integer',
        autoDiscoverRelation: true  // Arc will find related Post models
    )]
    public int $id;
    
    // Arc automatically discovers this relationship
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}

3. Enhanced Validation Groups

Use validation groups for different scenarios:

#[Property(
    type: 'string',
    required: true,
    groups: ['create', 'update'],
    minLength: 8
)]
public string $password;

#[Property(
    type: 'datetime',
    groups: ['admin_update']  // Only for admin updates
)]
public ?Carbon $verified_at = null;

4. Debug Tools

Use built-in debugging features:

// Enable debug mode
$model->enableArcDebug();

// Get transformation log
$log = $model->getTransformationLog();

// Analyze property usage
$analysis = $model->analyzeProperties();

Performance Improvements

Caching Enhancements

v2.0 includes improved caching:

// config/laravel-arc.php
'validation' => [
    'cache_rules' => true,
    'cache_duration' => 3600,
],
'pipeline' => [
    'cache_results' => true,
],

Memory Optimization

Better memory usage for large datasets:

class OptimizedModel extends Model
{
    use HasArcProperties;

    protected array $arcConfig = [
        'lazy_loading' => true,
        'batch_processing' => true,
    ];
}

Compatibility Layer

Backward Compatibility

v2.0 includes a compatibility layer for gradual migration:

// Enable v1 compatibility mode
'compatibility' => [
    'v1_attributes' => true,  // Support old attributes
    'v1_methods' => true,     // Support old method names
],

Deprecation Warnings

Enable deprecation warnings to identify legacy code:

'debug' => [
    'deprecation_warnings' => true,
    'log_deprecated_usage' => true,
],

Testing Migration

Updated Test Cases

Update your test cases for v2.0:

// Old test (v1.x)
class UserTest extends TestCase
{
    public function test_user_validation()
    {
        $user = new User();
        $this->assertFalse($user->validateAttributes(['name' => '']));
    }
}

// New test (v2.0)
class UserTest extends TestCase
{
    public function test_user_validation()
    {
        $user = new User();
        $validator = $user->validateData(['name' => '']);
        $this->assertTrue($validator->fails());
    }
}

Migration Test Suite

Create tests to verify your migration:

class MigrationTest extends TestCase
{
    public function test_v1_compatibility()
    {
        // Test that old code still works
        $user = new User();
        $this->assertTrue(method_exists($user, 'getValidationRules'));
    }
    
    public function test_v2_features()
    {
        // Test new v2.0 features
        $user = new User();
        $user->name = '  JOHN DOE  ';
        $this->assertEquals('John doe', $user->name); // Transformed
    }
}

Common Issues and Solutions

Issue 1: Class Not Found Errors

Problem: Old attribute classes not found

Solution:

composer dump-autoload
php artisan config:clear
php artisan cache:clear

Issue 2: Validation Rules Not Working

Problem: Old validation syntax not recognized

Solution: Update to new Property attribute syntax:

// Old
#[Validation('min:5|max:100')]

// New
#[Property(type: 'string', minLength: 5, maxLength: 100)]

Issue 3: Method Signature Changes

Problem: Method calls failing

Solution: Update method calls:

// Old
$isValid = $model->validateAttributes($data);

// New
$validator = $model->validateData($data);
$isValid = !$validator->fails();

Issue 4: Configuration Not Loading

Problem: Old config format not recognized

Solution: Republish and update configuration:

php artisan vendor:publish --provider="Grazulex\LaravelArc\LaravelArcServiceProvider" --tag="config" --force

Post-Migration Checklist

  • All models updated to use #[Property()] attribute
  • HasArcProperties trait added to all Arc models
  • Configuration file updated to v2.0 format
  • Custom validation rules migrated
  • Method calls updated to new signatures
  • Test suite passes with new version
  • Performance benchmarks meet expectations
  • Documentation updated for team
  • Deployment pipeline updated
  • Error monitoring configured for new features

Getting Help

If you encounter issues during migration:

  1. Check the FAQ for common solutions
  2. Review Breaking Changes for detailed change list
  3. Use the analysis command to identify issues: php artisan arc:analyze
  4. Search GitHub Issues for similar problems
  5. Create a new issue with your specific migration problem
  6. Join the Discussions for community help

Next Steps

After successful migration:

  1. Explore new features in Advanced Features
  2. Learn about transformations in Transformation Pipeline
  3. Set up auto-discovery in Auto-Discovery Relations
  4. Optimize performance using new caching features
  5. Update your team documentation with new patterns

Migration Complete! 🎉 You're now ready to take advantage of all the powerful features in Laravel Arc v2.0!