PHP code example of arnaldotomo / laravel-lusophone

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

    

arnaldotomo / laravel-lusophone example snippets


// Utilizador de Moçambique visita a aplicação
// Package detecta automaticamente MZ e adapta:

__('validation.tribute' => 'phone']);  
// → "O campo celular é obrigatório" (usa 'celular', não 'telemóvel')

// Utilizador de Portugal visita a mesma aplicação
// Package detecta automaticamente PT e adapta:

__('validation.O campo telemóvel é obrigatório"

use Illuminate\Support\Str;

// Formata automaticamente baseado na localização do utilizador
$price = 1500.50;
echo Str::lusophoneCurrency($price);
// Resultados automáticos:
// 🇵🇹 Portugal: "1.500,50 €"
// 🇲🇿 Moçambique: "1.500,50 MT"  
// 🇦🇴 Angola: "1.500,50 Kz"
// 🇧🇷 Brasil: "R$ 1.500,50"

echo $current = Lusophone::formatCurrency(1500.50, "MZ");
// 🇲🇿 Moçambique: "1.500,50 MT"  

use ArnaldoTomo\LaravelLusophone\Facades\Lusophone;

// Forçar região específica (útil para testes)
Lusophone::forceRegion('MZ');

// Obter região detectada
$region = Lusophone::detectRegion(); // 'MZ', 'PT', 'AO', etc.

// Obter informações do país
$info = Lusophone::getCountryInfo('MZ');
// [
//     'name' => 'Moçambique',
//     'currency' => 'MZN', 
//     'currency_symbol' => 'MT',
//     'phone_prefix' => '+258',
//     'formality' => 'mixed'
// ]

// Limpar cache de detecção
Lusophone::clearDetectionCache();

// Para casos onde precisa de validação específica
$rules = [
    // Portugal
    'nif' => 'f' => '

// Tradução com contexto cultural
Lusophone::contextualTranslate('welcome.message', 'business');
// Contexto empresarial: "Bem-vindo ao sistema, Estimado Cliente"

Lusophone::contextualTranslate('welcome.message', 'casual');  
// Contexto casual: "Olá! Bem-vindo"

// Detecção automática de contexto
$context = Lusophone::detectContext();
// 'business' (9h-17h, URLs /admin), 'government' (URLs /gov), 'casual' (outros)

// Verificar traduções em falta
$missing = Lusophone::getMissingTranslations([
    'validation.asTranslation('validation.email', 'MZ')) {
    // Tradução disponível para Moçambique
}

// routes/web.php
Route::post('/checkout', function (Request $request) {
    
    // Validação universal - funciona em qualquer país
    $validated = $request->validate([
        'name' => '   'address' => '    'message' => __('checkout.success'),
        'total' => Str::lusophoneCurrency(250.00),
        'currency' => $currency,
        'region' => $region,
    ]);
});

// app/Http/Controllers/AccountController.php
class AccountController extends Controller
{
    public function create(Request $request)
    {
        $region = Lusophone::detectRegion();
        
        // Regras de validação adaptáveis
        $rules = [
            'name' => 'ugal';
                $rules['iban'] = '   
            default:
                $rules['tax_id'] = ' ?? $validated['tax_id'],
            'region' => $region,
            'currency' => Lusophone::getCurrencyInfo($region)['code'],
        ]);
        
        return response()->json([
            'message' => __('account.created'),
            'account' => $account,
            'welcome_bonus' => Str::lusophoneCurrency(50.00),
        ]);
    }
}

// app/Http/Controllers/Api/UserController.php
class UserController extends Controller
{
    public function profile(Request $request)
    {
        $region = Lusophone::detectRegion();
        $user = $request->user();
        
        return response()->json([
            'user' => $user,
            'regional_info' => [
                'region' => $region,
                'country' => Lusophone::getCountryInfo($region)['name'],
                'currency' => Lusophone::getCurrencyInfo($region),
                'tax_id_label' => Lusophone::getTaxIdFieldName($region),
                'phone_label' => Lusophone::getPhoneFieldName($region),
            ],
            'localized_labels' => [
                'email' => __('attributes.email'),
                'phone' => __('attributes.phone'),
                'address' => __('attributes.address'),
            ],
            'validation_rules' => Lusophone::getValidationRules($region),
        ]);
    }
    
    public function updateProfile(Request $request)
    {
        $rules = [
            'name' => '

// resources/views/contact.blade.php
@php
    $context = Lusophone::detectContext();
    $region = Lusophone::detectRegion();
    $isBusinessHours = $context === 'business';
@endphp

<form method="POST" action="/contact">
    @csrf
    
    <div class="form-group">
        <label>{{ __('form.name') }}</label>
        <input type="text" name="name" 
    
    <div class="form-group">
        <label>{{ Lusophone::getPhoneFieldName($region) }}</label>
        <input type="tel" name="phone" placeholder="{{ Lusophone::getCountryInfo($region)['phone_prefix'] }}">
        @error('phone')
            <span class="error">{{ $message }}</span>
        @enderror
    </div>
    
    <div class="form-group">
        <label>{{ Lusophone::getTaxIdFieldName($region) }} (opcional)</label>
        <input type="text" name="tax_id">
        @error('tax_id')
            <span class="error">{{ $message }}</span>
        @enderror
    </div>
    
    <div class="form-group">
        <label>{{ __('form.message') }}</label>
        <textarea name="message" 

// config/lusophone.php
return [
    // Detecção automática
    'auto_detect' => env('LUSOPHONE_AUTO_DETECT', true),
    'auto_set_locale' => env('LUSOPHONE_AUTO_SET_LOCALE', true),
    'default_region' => env('LUSOPHONE_DEFAULT_REGION', 'PT'),
    'force_region' => env('LUSOPHONE_FORCE_REGION'),
    
    // Contexto cultural
    'cultural_context' => env('LUSOPHONE_CULTURAL_CONTEXT', true),
    
    // Performance
    'cache_detections' => env('LUSOPHONE_CACHE', true),
    'cache_ttl' => env('LUSOPHONE_CACHE_TTL', 3600),
    
    // Regiões específicas
    'regions' => [
        'MZ' => [
            'enabled' => true,
            'locale' => 'pt_MZ',
            'timezone' => 'Africa/Maputo',
            'formality_default' => 'mixed',
        ],
        // ... outras regiões
    ],
];

// tests/Feature/LusophoneTest.php
use ArnaldoTomo\LaravelLusophone\Facades\Lusophone;

class LusophoneTest extends TestCase
{
    /** @test */
    public function it_validates_mozambican_documents()
    {
        // Forçar região para teste
        Lusophone::forceRegion('MZ');
        
        $response = $this->post('/api/users', [
            'name' => 'João Silva',
            'email' => '[email protected]',
            'nuit' => '123456789',
            'phone' => '821234567',
        ]);
        
        $response->assertStatus(201);
        $this->assertDatabaseHas('users', [
            'email' => '[email protected]',
        ]);
    }
    
    /** @test */
    public function it_formats_currency_by_region()
    {
        Lusophone::forceRegion('PT');
        $this->assertEquals('100,00 €', Str::lusophoneCurrency(100));
        
        Lusophone::forceRegion('MZ');
        $this->assertEquals('100,00 MT', Str::lusophoneCurrency(100));
        
        Lusophone::forceRegion('BR');
        $this->assertEquals('R$ 100,00', Str::lusophoneCurrency(100));
    }
    
    /** @test */
    public function it_adapts_validation_messages()
    {
        Lusophone::forceRegion('PT');
        
        $validator = Validator::make([], ['email' => '

// resources/lang/pt/custom.php
return [
    'welcome' => [
        'business' => 'Bem-vindo ao sistema, Estimado Cliente',
        'casual' => 'Olá! Bem-vindo',
        'government' => 'Respeitosos cumprimentos',
    ],
    'checkout' => [
        'total' => 'Total a pagar: :amount',
        'success' => 'Compra realizada com sucesso',
    ],
];

// app/Providers/AppServiceProvider.php
use Illuminate\Support\Str;
use ArnaldoTomo\LaravelLusophone\Facades\Lusophone;

public function boot()
{
    // Macro para formatação de percentagem
    Str::macro('lusophonePercentage', function ($value, $region = null) {
        $region = $region ?: Lusophone::detectRegion();
        $formatted = number_format($value, 1, ',', ' ');
        return "{$formatted}%";
    });
    
    // Macro para formatação de data
    \Carbon\Carbon::macro('lusophoneFormat', function ($region = null) {
        $region = $region ?: Lusophone::detectRegion();
        
        return match($region) {
            'US', 'TL' => $this->format('m/d/Y'),
            default => $this->format('d/m/Y')
        };
    });
}

// app/Providers/AppServiceProvider.php
use Illuminate\Support\Facades\Validator;

public function boot()
{
    // Validador personalizado para Moçambique
    Validator::extend('mz_phone_extended', function ($attribute, $value) {
        // Lógica personalizada para telefones moçambicanos
        return preg_match('/^(\+258|258)?[82][0-9]{7}$/', $value);
    }, 'O :attribute deve ser um número de telemóvel moçambicano válido.');
}

// Verificar detecção
dd(Lusophone::detectRegion());

// Forçar região temporariamente
Lusophone::forceRegion('MZ');

// Limpar cache
Lusophone::clearDetectionCache();

// Testar validações específicas
php artisan lusophone:detect --test-validation --region=MZ

// Verificar se região suporta validação
$supported = Lusophone::isLusophoneCountry('MZ'); // true

// config/lusophone.php
'debug' => [
    'log_detections' => env('LUSOPHONE_LOG_DETECTIONS', false),
    'show_detection_headers' => env('LUSOPHONE_DEBUG_HEADERS', false),
],

use ArnaldoTomo\LaravelLusophone\Facades\Lusophone;

// Detecção
Lusophone::detectRegion(): string
Lusophone::getCountryInfo(?string $region): array
Lusophone::getAllCountries(): array
Lusophone::isLusophoneCountry(string $country): bool

// Controle
Lusophone::forceRegion(string $region): static
Lusophone::clearDetectionCache(): static

// Validação
Lusophone::validateTaxId(string $value, ?string $region): bool
Lusophone::validatePhone(string $value, ?string $region): bool
Lusophone::validatePostalCode(string $value, ?string $region): bool
Lusophone::getTaxIdFieldName(?string $region): string
Lusophone::getPhoneFieldName(?string $region): string

// Formatação
Lusophone::formatCurrency(float $amount, ?string $region): string
Lusophone::getCurrencyInfo(?string $region): array

// Tradução
Lusophone::translate(string $key, array $replace = [], ?string $region): string
Lusophone::contextualTranslate(string $key, string $context = 'general', array $replace = [], ?string $region): string
Lusophone::detectContext(): string
Lusophone::hasTranslation(string $key, ?string $region): bool

use Illuminate\Support\Str;

// Formatação de moeda
Str::lusophoneCurrency(float $amount, ?string $region): string

// Formatação de números
Str::lusophoneNumber(float $number, int $decimals = 2, ?string $region): string

// Tradução
Str::lusophoneTranslate(string $key, array $replace = [], ?string $region): string

// Países lusófonos
collect()->lusophoneCountries(): Collection

// Universais
'lusophone_tax_id'    // NIF/NUIT/CPF automático
'lusophone_phone'     // Telefone formato local
'lusophone_postal'    // Código postal formato local

// Específicas por país
'nif_portugal'        // NIF português (9 dígitos + algoritmo)
'nuit_mozambique'     // NUIT moçambicano (9 dígitos)
'cpf_brazil'          // CPF brasileiro (11 dígitos + algoritmo)
'nif_angola'          // NIF angolano (10 dígitos)
'nif_cape_verde'      // NIF cabo-verdiano (9 dígitos)

// routes/web.php
Route::get('/test', function () {
    $region = Lusophone::detectRegion();
    $country = Lusophone::getCountryInfo($region)['name'];
    $price = Str::lusophoneCurrency(99.90);
    
    return "Olá de {$country}! Preço: {$price}";
});

// Adicionar ao seu FormRequest existente
public function rules()
{
    return [
        'name' => ' acontece aqui
        'phone' => '
bash
# Publicar ficheiros de idioma (opcional - funciona sem publicar)
php artisan vendor:publish --tag=lusophone-lang

# Publicar configuração (opcional - padrões sensatos fornecidos)
php artisan vendor:publish --tag=lusophone-config
bash
# Comando de setup interativo
php artisan lusophone:setup

# Ou forçar região específica
php artisan lusophone:setup --region=MZ --publish
bash
# Setup inicial interativo
php artisan lusophone:setup

# Setup com região específica
php artisan lusophone:setup --region=MZ

# Setup com publicação de ficheiros
php artisan lusophone:setup --publish

# Setup completo
php artisan lusophone:setup --region=MZ --publish
bash
# Análise geral das traduções
php artisan lusophone:analyze

# Verificar traduções em falta
php artisan lusophone:analyze --missing

# Verificar cobertura de traduções
php artisan lusophone:analyze --coverage

# Exportar análise para ficheiro
php artisan lusophone:analyze --export=json
php artisan lusophone:analyze --export=csv
bash
# Testar detecção atual
php artisan lusophone:detect

# Testar região específica
php artisan lusophone:detect --region=PT

# Testar validações
php artisan lusophone:detect --test-validation

# Testar formatação de moeda
php artisan lusophone:detect --test-currency

# Limpar cache de detecção
php artisan lusophone:detect --clear-cache

# Teste completo
php artisan lusophone:detect --region=MZ --test-validation --test-currency
bash
# Publicar ficheiros de idioma
php artisan vendor:publish --tag=lusophone-lang --force

# Verificar traduções
php artisan lusophone:analyze --missing
bash
# Limpar todos os caches
php artisan cache:clear
php artisan config:clear
php artisan lusophone:detect --clear-cache
bash
php artisan lusophone:detect --test-validation --test-currency