Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Phoneformatterbundle Laravel Package

alpixel/phoneformatterbundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require alpixel/phoneformatterbundle
    
  2. Register the Bundle Add to config/bundles.php (Symfony 3.3+):

    return [
        // ...
        Alpixel\Bundle\PhoneFormatterBundle\AlpixelPhoneFormatterBundle::class => ['all' => true],
    ];
    

    (For Symfony 2.x, update AppKernel.php as shown in the README.)

  3. First Use Case Format a raw phone number in a controller:

    use Alpixel\Bundle\PhoneFormatterBundle\Helper\PhoneNumberFormat;
    
    $formatter = $this->get('alpixel.helper.phone_formatter');
    $formatted = $formatter->format('+1234567890', PhoneNumberFormat::NATIONAL, 'US');
    // Output: "(123) 456-7890"
    

Implementation Patterns

Core Workflows

  1. Controller/Service Integration Inject the helper via dependency injection:

    use Alpixel\Bundle\PhoneFormatterBundle\Helper\PhoneFormatterInterface;
    
    class UserController extends Controller
    {
        public function __construct(PhoneFormatterInterface $formatter) {
            $this->formatter = $formatter;
        }
    
        public function showProfile() {
            $phone = $this->formatter->format($rawPhone, PhoneNumberFormat::E164, 'FR');
            // ...
        }
    }
    
  2. Twig Templating Format directly in views:

    {{ user.phone|phone_format('NATIONAL', 'GB') }}
    

    (Supports all formats: INTERNATIONAL, NATIONAL, E164, AUTO.)

  3. Form Validation Clean and validate input before storage:

    $cleaned = $formatter->format($request->get('phone'), PhoneNumberFormat::E164, 'DE');
    if (!$cleaned) {
        throw new \InvalidArgumentException('Invalid phone number');
    }
    
  4. Dynamic Locale Handling Use AUTO format with the user’s locale:

    $locale = $this->getUser()->getLocale();
    $formatted = $formatter->format($rawPhone, PhoneNumberFormat::AUTO, $locale);
    

Integration Tips

  • Symfony Forms: Use a custom type to auto-format phone numbers on submit.
  • API Responses: Normalize phone numbers to E164 for consistency.
  • Database Storage: Store in E164 format, display dynamically in the UI.

Gotchas and Tips

Pitfalls

  1. Deprecated Symfony 2.x Support

    • The bundle targets Symfony 2.8/3.0 but lacks modern Symfony (4.x/5.x) compatibility.
    • Workaround: Use a wrapper service or fork the package for newer Symfony versions.
  2. Locale-Specific Formatting

    • Some country codes (e.g., US, GB) work perfectly, while others (e.g., JP, IN) may produce unexpected results.
    • Tip: Test edge cases with libphonenumber-for-php's test data.
  3. Input Sanitization

    • The formatter assumes input is a string. Non-string inputs (e.g., null, int) may cause errors.
    • Fix: Add validation:
      if (!is_string($rawPhone)) {
          throw new \InvalidArgumentException('Phone number must be a string');
      }
      
  4. Twig Extension Scope

    • The Twig filter is globally available but may conflict with other bundles using phone_format.
    • Tip: Rename the filter in your template engine if needed (e.g., custom_phone_format).

Debugging

  • Check Raw Output: Use PhoneNumberFormat::E164 to debug the parsed number before formatting:
    $e164 = $formatter->format($rawPhone, PhoneNumberFormat::E164, 'FR');
    
  • LibphoneNumber Errors: Underlying libphonenumber-for-php may throw exceptions for invalid numbers. Catch them:
    try {
        $formatted = $formatter->format($rawPhone, PhoneNumberFormat::NATIONAL, 'IT');
    } catch (\Exception $e) {
        // Handle invalid number (e.g., log or return default)
    }
    

Extension Points

  1. Custom Formats Extend the bundle by creating a decorator service:

    # config/services.yaml
    services:
        app.phone_formatter.decorator:
            decorates: alpixel.helper.phone_formatter
            arguments: ['@app.phone_formatter.decorator.inner']
    

    Then override the format() method in your decorator.

  2. Add New Country Codes The bundle relies on libphonenumber-for-php. Extend its metadata if needed:

    use libphonenumber\PhoneNumberUtil;
    
    $util = PhoneNumberUtil::getInstance();
    $util->setRegionCodeForNumber($phoneNumber, 'XX'); // Custom region
    
  3. Performance

    • The formatter is stateless and thread-safe. Cache the service if used frequently in high-traffic endpoints.
    • Example:
      services:
          alpixel.helper.phone_formatter:
              public: false
              tags: ['container.cacheable']
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky