PHP code example of upward / formatters

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

    

upward / formatters example snippets


// Creating and validating a CPF Document
use Upward\Formatters\Documents\CpfDocument;
use Upward\Formatters\Document;

// Initialize with a CPF number
$cpf = new CpfDocument(value: '12345678909');
$document = new Document($cpf);

// Validate the CPF (throws exception if invalid)
try {
    $document->validate();
    echo "CPF is valid!";
} catch (\Exception) {
    //
}

// Format the CPF with standard mask
echo $document->format();    // Outputs: 123.456.789-09

// Create an anonymized version for privacy
echo $document->anonymize(); // Outputs: 123.***.***-09

// Creating and working with CNPJ Documents
use Upward\Formatters\Documents\CnpjDocument;
use Upward\Formatters\Document;

// Initialize with a CNPJ number
$cnpj = new CnpjDocument(value: '12345678000195');
$document = new Document($cnpj);

// Validate the CNPJ
try {
    $document->validate();
    echo "CNPJ is valid and can be used!";
} catch (\Exception) {
    //
}

// Apply standard CNPJ formatting
echo $document->format();    // Outputs: 12.345.678/0001-95

// Generate privacy-safe version for displaying
echo $document->anonymize(); // Outputs: 12.***.***/0001-95

// Working with multiple documents
use Upward\Formatters\Folder;
use Upward\Formatters\Documents\CpfDocument;
use Upward\Formatters\Documents\CnpjDocument;
use Upward\Formatters\Document;
use Upward\Formatters\Exceptions\Documents\InvalidDocumentException;

// Create a document collection
$folder = new Folder();

// Add different document types
$folder->push(new Document(new CpfDocument('12345678909')));
$folder->push(new Document(new CnpjDocument('12345678000195')));

// Count documents in collection
echo "Total documents: " . count($folder); // Outputs: 2

// Filter for only valid documents
$validDocs = $folder->valid();

// Process each document in the collection
$folder->each(callback: static function (Document $document, string | int $key): void {
    // Perform operations on each document
});

// Validate all documents at once (will throw exception on first invalid document)
try {
    $folder->validate();
    echo "All documents are valid!";
} catch (InvalidDocumentException) {
    //
}