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

Phone Number Bundle Laravel Package

20steps/phone-number-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require misd/phone-number-bundle
    
  2. Enable Bundle in config/bundles.php:
    return [
        // ...
        Misd\PhoneNumberBundle\MisdPhoneNumberBundle::class => ['all' => true],
    ];
    
  3. First Use Case: Validate and format a phone number in a controller:
    use Misd\PhoneNumberBundle\PhoneNumber\PhoneNumberUtil;
    
    public function validatePhone(Request $request)
    {
        $phoneUtil = new PhoneNumberUtil();
        $phoneNumber = $phoneUtil->parse('+14155552671', 'US');
    
        if ($phoneUtil->isValidNumber($phoneNumber)) {
            $formatted = $phoneUtil->format($phoneNumber, \libphonenumber\PhoneNumberFormat::E164);
            return new JsonResponse(['valid' => true, 'formatted' => $formatted]);
        }
    
        return new JsonResponse(['valid' => false], 400);
    }
    

Where to Look First

  • Service Container: The bundle provides a phone_number.util service (check config/services.yaml).
  • Validation: Use PhoneNumberUtil for parsing, validation, and formatting.
  • Doctrine Integration: If using Doctrine, check for custom types or listeners (if available).

Implementation Patterns

Common Workflows

  1. Form Validation:

    use Symfony\Component\Validator\Constraints as Assert;
    use Misd\PhoneNumberBundle\Validator\Constraints\ValidPhoneNumber;
    
    $builder->add('phone', TextType::class, [
        'constraints' => [
            new ValidPhoneNumber(['countryCode' => 'US']),
        ],
    ]);
    
  2. Phone Number Parsing in Services:

    public function __construct(private PhoneNumberUtil $phoneUtil) {}
    
    public function processPhone(string $rawPhone): string
    {
        $phone = $this->phoneUtil->parse($rawPhone);
        return $this->phoneUtil->format($phone, \libphonenumber\PhoneNumberFormat::NATIONAL);
    }
    
  3. Internationalization:

    $phoneUtil = new PhoneNumberUtil();
    $phone = $phoneUtil->parse('02079460000', 'GB'); // UK number
    $geocode = $phoneUtil->getRegionCodeForNumber($phone); // Returns 'GB'
    
  4. Doctrine Entity Integration (if extended):

    use Misd\PhoneNumberBundle\Doctrine\Types\PhoneNumberType;
    
    /**
     * @ORM\Column(type="phone_number")
     */
    private $phone;
    

Integration Tips

  • Symfony Forms: Use Misd\PhoneNumberBundle\Form\Type\PhoneNumberType for form fields.
  • API Responses: Normalize phone numbers to E164 format (PhoneNumberFormat::E164) for consistency.
  • Testing: Mock PhoneNumberUtil for unit tests:
    $this->createMock(PhoneNumberUtil::class);
    

Gotchas and Tips

Pitfalls

  1. Country Code Ambiguity:

    • Some numbers (e.g., +1 vs. +44) may resolve to unexpected regions. Use setDefaultRegion() if needed:
      $phoneUtil->setDefaultRegion('US');
      
  2. Performance:

    • Parsing is lightweight, but avoid parsing the same number repeatedly in loops. Cache results if needed.
  3. Deprecated Methods:

  4. Doctrine Limitations:

    • The bundle may not include Doctrine types out-of-the-box. Extend it if needed:
      // Example custom type (if not provided)
      class PhoneNumberType extends Type {
          public function convertToDatabaseValue($value, AbstractPlatform $platform)
          {
              return $value->getNationalNumber();
          }
      }
      

Debugging

  • Invalid Numbers:

    • Use isValidNumber() to check validity. For edge cases, log the raw input and parsed output:
      try {
          $phone = $phoneUtil->parse($rawInput);
      } catch (\libphonenumber\NumberParseException $e) {
          // Handle exception (e.g., log $rawInput)
      }
      
  • Region Mismatches:

    • If getRegionCodeForNumber() returns unexpected results, verify the input format or use getNumberType() to check for mobile/landline.

Extension Points

  1. Custom Validation: Extend the ValidPhoneNumber constraint or create a custom validator:

    class CustomPhoneValidator extends ConstraintValidator {
        public function validate($value, Constraint $constraint) {
            $phoneUtil = new PhoneNumberUtil();
            $phone = $phoneUtil->parse($value);
            if (!$phoneUtil->isValidNumber($phone)) {
                $this->context->buildViolation($constraint->message)
                    ->addViolation();
            }
        }
    }
    
  2. Phone Number Storage: Store parsed numbers in a normalized format (e.g., E164) in the database to avoid reprocessing:

    $phoneUtil->format($phone, \libphonenumber\PhoneNumberFormat::E164);
    
  3. Localization: Override the default region for parsing by setting it in the PhoneNumberUtil instance:

    $phoneUtil->setDefaultRegion('DE'); // Default to Germany
    
  4. Testing: Use the PhoneNumberUtil constructor to inject a custom PhoneNumberMetadata for testing:

    $metadata = new PhoneNumberMetadata();
    $phoneUtil = new PhoneNumberUtil($metadata);
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware