PHP code example of hdaklue / polish

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

    

hdaklue / polish example snippets


// Before: Scattered, inconsistent, unmaintainable chaos
substr($ulid, -6)           // In Filament column
substr($ulid, -6)           // In Livewire computed property  
substr($ulid, -6)           // In Blade template
substr($ulid, -6)           // In API resource
substr($ulid, -6)           // In notification
substr($ulid, -6)           // In DTO transformation
// ... and 15 other places you'll inevitably forget about

// After: Centralized, consistent, maintainable elegance
UlidPolisher::short($ulid)  // Everywhere, every time, perfectly consistent



namespace App\Polishers;

use Hdaklue\Polish\BasePolisher;

class UlidPolisher extends BasePolisher
{
    public static function short(string $ulid): string
    {
        return substr($ulid, -7); // Change this once, updates everywhere
    }
    
    public static function display(string $ulid): string
    {
        return sprintf('v-%s', static::short($ulid));
    }
    
    public static function adminFormat(string $ulid): string
    {
        return strtoupper(static::short($ulid));
    }
}

// ✅ In Filament admin panels
Tables\Columns\TextColumn::make('version_id')
    ->label('Version')
    ->formatStateUsing(fn ($state) => UlidPolisher::display($state))

// ✅ In Livewire components  
#[Computed]
public function versionBadge(): string
{
    return UlidPolisher::adminFormat($this->version_id);
}

// ✅ In Blade templates
<span class="font-mono">{{ UlidPolisher::short($model->version_id) }}</span>
<div class="badge">{{ UlidPolisher::display($model->version_id) }}</div>

// ✅ In API resources
'version' => UlidPolisher::short($this->version_id),
'display_version' => UlidPolisher::display($this->version_id),

// ✅ In DTOs, transformers, anywhere you need formatted data
$dto->version = UlidPolisher::short($rawData['version_id']);
$processedData = array_map(
    fn($item) => UlidPolisher::display($item['id']), 
    $apiResponse
);

use Hdaklue\Polish\NumberPolisher;

// Ordinal numbers - perfect for rankings, dates, positions
NumberPolisher::ordinal(1);    // "1st" 
NumberPolisher::ordinal(22);   // "22nd"  
NumberPolisher::ordinal(103);  // "103rd"

// Roman numerals (1-399) - great for versions, chapters, generations
NumberPolisher::roman(42);     // "XLII"
NumberPolisher::roman(399);    // "CCCXCIX"
NumberPolisher::roman(400);    // "400" (smart fallback for out-of-range)

// Number ranges - clean display for filters, reports, spans
NumberPolisher::range(10, 20);           // "10–20" (em dash, not hyphen)
NumberPolisher::range(1, 5, ' to ');     // "1 to 5" (custom separator)

// Score formatting - test scores, ratings, performance metrics  
NumberPolisher::score(85, 100);          // "85/100"
NumberPolisher::score(7, 10);            // "7/10"

// Visual star ratings - reviews, quality indicators, user ratings
NumberPolisher::rating(4.5);             // "★★★★☆" (out of 5 stars)
NumberPolisher::rating(7.5, 10);         // "★★★★★★★☆☆☆" (custom max)

use Hdaklue\Polish\StringPolisher;

// Smart masking with patterns
StringPolisher::smartMask('[email protected]', 'email');    // "jo****@email.com"
StringPolisher::smartMask('555-123-4567', 'phone');      // "555-***-4567"
StringPolisher::smartMask('4111-1111-1111-1111', 'card'); // "4111-****-****-1111"

// Intelligent excerpts with keyword centering
$text = 'Long article with important keyword somewhere in middle...';
StringPolisher::excerpt($text, 50, 'keyword');           // "...important keyword somewhere..."

// Technical string humanization
StringPolisher::humanize('user_profile_api');            // "User Profile API"
StringPolisher::humanize('payment-gateway-config');      // "Payment Gateway Config"

// Name initials
StringPolisher::initials('John Doe');                    // "JD"
StringPolisher::initials('John Michael Smith', 3);       // "JMS"

// Social media formatting  
StringPolisher::mention('John Doe');                     // "@john_doe"
StringPolisher::hashtag('React Native');                 // "#ReactNative"

class CurrencyPolisher extends BasePolisher
{
    public static function money(int $cents): string
    {
        return '$' . number_format($cents / 100, 2);
    }
    
    public static function compact(int $cents): string
    {
        $amount = $cents / 100;
        if ($amount >= 1000000) {
            return '$' . round($amount / 1000000, 1) . 'M';
        }
        if ($amount >= 1000) {
            return '$' . round($amount / 1000, 1) . 'K';
        }
        return static::money($cents);
    }
}

class OrderStatusPolisher extends BasePolisher
{
    public static function badge(string $status): string
    {
        return match($status) {
            'pending' => '🟡 Pending',
            'processing' => '🔵 Processing', 
            'shipped' => '🟢 Shipped',
            'delivered' => '✅ Delivered',
            'cancelled' => '🔴 Cancelled',
            default => '❓ Unknown'
        };
    }
    
    public static function color(string $status): string
    {
        return match($status) {
            'pending' => 'warning',
            'processing' => 'info',
            'shipped' => 'success', 
            'delivered' => 'success',
            'cancelled' => 'danger',
            default => 'gray'
        };
    }
}

class DatePolisher extends BasePolisher
{
    public static function relative(\DateTimeInterface $date): string
    {
        return $date->diffForHumans();
    }
    
    public static function short(\DateTimeInterface $date): string
    {
        return $date->format('M j, Y');
    }
    
    public static function time(\DateTimeInterface $date): string
    {
        return $date->format('g:i A');
    }
}

// In table columns
TextColumn::make('amount')
    ->formatStateUsing(fn ($state) => CurrencyPolisher::money($state))

// In forms
Placeholder::make('formatted_total')
    ->content(fn ($record) => CurrencyPolisher::compact($record->total))

class OrderComponent extends Component
{
    #[Computed]
    public function statusBadge(): string
    {
        return OrderStatusPolisher::badge($this->order->status);
    }
    
    #[Computed] 
    public function formattedTotal(): string
    {
        return CurrencyPolisher::money($this->order->total);
    }
}

// In your blade components
<x-status-badge :color="OrderStatusPolisher::color($order->status)">
    {{ OrderStatusPolisher::badge($order->status) }}
</x-status-badge>

<span class="font-mono">
    {{ UlidPolisher::short($model->id) }}
</span>

class OrderResource extends JsonResource
{
    public function toArray($request): array
    {
        return [
            'id' => UlidPolisher::short($this->id),
            'status' => OrderStatusPolisher::badge($this->status),
            'total' => CurrencyPolisher::money($this->total),
            'created_at' => DatePolisher::relative($this->created_at),
        ];
    }
}

// E-commerce specific formatting
class ProductPolisher extends BasePolisher
{
    public static function sku(string $sku): string
    {
        return strtoupper(substr($sku, 0, 3) . '-' . substr($sku, 3));
    }
    
    public static function availability(int $stock): string
    {
        return match(true) {
            $stock === 0 => '🔴 Out of Stock',
            $stock < 5 => '🟡 Low Stock (' . $stock . ' left)',
            $stock < 20 => '🟢 In Stock (' . $stock . ' available)',
            default => '🟢 In Stock (20+ available)'
        };
    }
    
    public static function badge(float $rating, int $reviews): string
    {
        if ($reviews < 10) return '';
        if ($rating >= 4.5) return '⭐ Bestseller';
        if ($rating >= 4.0) return '👍 Recommended';
        return '';
    }
}

// Fun and creative formatters
class CreativePolisher extends BasePolisher
{
    public static function progress(int $current, int $total): string
    {
        $percentage = ($current / $total) * 100;
        $filled = floor($percentage / 10);
        return str_repeat('█', $filled) . str_repeat('░', 10 - $filled) . " {$percentage}%";
    }
    
    public static function mood(string $sentiment): string
    {
        return match($sentiment) {
            'positive' => '😊 ' . $sentiment,
            'negative' => '😞 ' . $sentiment,  
            'neutral' => '😐 ' . $sentiment,
            default => '🤷 unknown'
        };
    }
    
    public static function fileIcon(string $extension): string
    {
        return match($extension) {
            'pdf' => '📄',
            'jpg', 'png', 'gif' => '🖼️',
            'mp4', 'mov' => '🎬',
            'mp3', 'wav' => '🎵',
            'zip', 'tar' => '🗜️',
            default => '📁'
        };
    }
}

// API and external service formatters  
class IntegrationPolisher extends BasePolisher
{
    public static function githubUrl(string $repo): string
    {
        return "https://github.com/{$repo}";
    }
    
    public static function slackMention(string $userId): string
    {
        return "<@{$userId}>";
    }
    
    public static function discordEmbed(string $title, string $description): array
    {
        return [
            'embeds' => [[
                'title' => $title,
                'description' => $description,
                'color' => 0x00ff00
            ]]
        ];
    }
}

class MyPolisher extends BasePolisher
{
    /**
     * Format a complex business identifier with validation
     */
    public static function businessId(string $id): string
    {
        if (empty($id) || strlen($id) < 6) {
            return $id; // Return as-is for invalid input
        }
        
        return strtoupper(substr($id, 0, 2)) . '-' . 
               substr($id, 2, 4) . '-' . 
               substr($id, 6);
    }
}

UlidPolisher::invalidMethod($ulid); 
// Throws: UnsupportedPolisherMethodException: 
// Polisher [App\Polishers\UlidPolisher] does not support static polish method [invalidMethod].

class TextPolisher extends BasePolisher
{
    public static function clean(string $text): string
    {
        return trim(strip_tags($text));
    }
    
    public static function limit(string $text, int $limit = 100): string
    {
        return Str::limit($text, $limit);
    }
}

// Chain operations
$clean = TextPolisher::limit(TextPolisher::clean($userInput), 50);

   public static function displayName(string $firstName, string $lastName): string
   {
       return "{$firstName} {$lastName}";
   }
   

   {{ UserPolisher::displayName($user->first_name, $user->last_name) }}
   
bash
   php artisan polisher:make User