PHP code example of grazulex / laravel-modelschema

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

    

grazulex / laravel-modelschema example snippets


use Grazulex\LaravelModelschema\Services\SchemaService;

$schemaService = new SchemaService();

// Parse and separate core from extensions
$result = $schemaService->parseAndSeparateSchema($yamlContent);
// Returns: ['core' => [...], 'extensions' => [...]]

// Validate only the core schema
$errors = $schemaService->validateCoreSchema($yamlContent);

// Extract structured data for generation
$data = $schemaService->extractCoreContentForGeneration($yamlContent);

// 1. Generate complete YAML from stub + app data
$completeYaml = $schemaService->generateCompleteYamlFromStub(
    'user.schema.stub',
    ['MODEL_NAME' => 'User', 'TABLE_NAME' => 'users'],
    $appExtensionData
);

// 2. Validate the complete YAML (focuses on core section)
$errors = $schemaService->validateFromCompleteAppYaml($completeYaml);

// 3. Extract all generation data as insertable fragments
$generationData = $schemaService->getGenerationDataFromCompleteYaml($completeYaml);

// 4. Use fragments in your application
$modelFragment = json_decode($generationData['generation_data']['model']['json'], true);
$migrationFragment = json_decode($generationData['generation_data']['migration']['json'], true);

use Grazulex\LaravelModelschema\Services\GenerationService;

$generationService = new GenerationService();

// Generate all fragments for a schema
$fragments = $generationService->generateAll($schema);

// Result structure:
// [
//   'model' => ['json' => '{"model": {...}}', 'yaml' => 'model: {...}'],
//   'migration' => ['json' => '{"migration": {...}}', 'yaml' => 'migration: {...}'],
//   'requests' => ['json' => '{"requests": {...}}', 'yaml' => 'requests: {...}'],
//   'resources' => ['json' => '{"resources": {...}}', 'yaml' => 'resources: {...}'],
//   'factory' => ['json' => '{"factory": {...}}', 'yaml' => 'factory: {...}'],
//   'seeder' => ['json' => '{"seeder": {...}}', 'yaml' => 'seeder: {...}'],
//   'controllers' => ['json' => '{"controllers": {...}}', 'yaml' => 'controllers: {...}'],
//   'tests' => ['json' => '{"tests": {...}}', 'yaml' => 'tests: {...}'],
//   'policies' => ['json' => '{"policies": {...}}', 'yaml' => 'policies: {...}'],
//   'observers' => ['json' => '{"observers": {...}}', 'yaml' => 'observers: {...}'],
//   'services' => ['json' => '{"services": {...}}', 'yaml' => 'services: {...}'],
//   'actions' => ['json' => '{"actions": {...}}', 'yaml' => 'actions: {...}'],
//   'rules' => ['json' => '{"rules": {...}}', 'yaml' => 'rules: {...}']
// ]

// Generate specific components
$observerFragment = $generationService->generateObservers($schema);
$serviceFragment = $generationService->generateServices($schema);
$actionFragment = $generationService->generateActions($schema);
$ruleFragment = $generationService->generateRules($schema);

// Generate multiple new components
$fragments = $generationService->generateMultiple($schema, [
    'observers', 'services', 'actions', 'rules'
]);

// Generate everything including new components
$allFragments = $generationService->generateAll($schema, [
    'model' => true,
    'migration' => true,
    'requests' => true,
    'resources' => true,
    'factory' => true,
    'seeder' => true,
    'controllers' => true,
    'tests' => true,
    'policies' => true,
    'observers' => true,    // New
    'services' => true,     // New
    'actions' => true,      // New
    'rules' => true,        // New
]);

use Grazulex\LaravelModelschema\Support\FieldTypePluginManager;

$manager = new FieldTypePluginManager();

// Register a custom plugin
$manager->registerPlugin(new CustomFieldTypePlugin());

// Auto-discover plugins in specific paths  
$manager->discoverPlugins([
    'App\\FieldTypes\\*Plugin',
    'Custom\\Packages\\*FieldTypePlugin'
]);

// Get all registered plugins
$plugins = $manager->getAllPlugins();

use Grazulex\LaravelModelschema\Support\FieldTypePlugin;

class UrlFieldTypePlugin extends FieldTypePlugin
{
    protected string $version = '1.0.0';
    protected string $author = 'Your Name';
    protected string $description = 'Advanced URL field with validation traits';

    public function __construct()
    {
        // Define custom attributes using trait-based configuration
        $this->customAttributes = [
            'schemes', 'verify_ssl', 'timeout', 'domain_whitelist', 'max_redirects'
        ];
        
        // Configure each attribute with validation traits
        $this->customAttributeConfig = [
            'schemes' => [
                'type' => 'array',
                'default' => ['http', 'https'],
                'enum' => ['http', 'https', 'ftp', 'ftps'],
                'description' => 'Allowed URL schemes for validation'
            ],
            'verify_ssl' => [
                'type' => 'boolean',
                'default' => true,
                'description' => 'Enable SSL certificate verification'
            ],
            'timeout' => [
                'type' => 'integer',
                'min' => 1,
                'max' => 300,
                'default' => 30,
                'description' => 'Connection timeout in seconds'
            ],
            'domain_whitelist' => [
                'type' => 'array',
                '

// Numeric validation traits
'timeout' => [
    'type' => 'integer',
    'min' => 1,
    'max' => 300,
    'default' => 30,
    'transform' => fn($value) => (int) $value // Type transformation trait
],

// Array validation traits with enum constraints
'schemes' => [
    'type' => 'array',
    'enum' => ['http', 'https', 'ftp', 'ftps'],
    'default' => ['http', 'https'],
    'validator' => function($schemes): array {
        // Custom validation trait
        return array_filter($schemes, fn($s) => in_array($s, ['http', 'https']));
    }
],

// Complex custom validator traits
'domain_pattern' => [
    'type' => 'string',
    'validator' => function($pattern): array {
        if (!preg_match('/^\/.*\/[gimxs]*$/', $pattern)) {
            return ['Domain pattern must be a valid regex'];
        }
        return [];
    }
]

// 1. Parent app generates complete YAML
$yaml = $schemaService->generateCompleteYamlFromStub('user.schema.stub', [
    'MODEL_NAME' => 'User',
    'TABLE_NAME' => 'users'
], $parentAppData);

// 2. Parent app validates the schema
$errors = $schemaService->validateFromCompleteAppYaml($yaml);
if (!empty($errors)) {
    throw new ValidationException($errors);
}

// 3. Parent app extracts generation fragments
$data = $schemaService->getGenerationDataFromCompleteYaml($yaml);

// 4. Parent app integrates fragments into its own files
$parentAppGenerator->generateModelFile($data['generation_data']['model']['json']);
$parentAppGenerator->generateMigrationFile($data['generation_data']['migration']['json']);
// ... etc for requests, resources, factory, seeder