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

Gls Bundle Laravel Package

answear/gls-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require answear/gls-bundle
    

    The bundle auto-registers in config/bundles.php via Symfony Flex.

  2. Configure: Add your supported countries (e.g., HU, SK) in config/packages/answear_gls.yaml:

    answear_gls:
        countryCode: HU|SK
        logger: app.logger  # Optional: Custom PSR-3 logger
    
  3. First Use Case: Fetch parcel shops via the service container:

    $parcelShops = $this->get('Answear\GlsBundle\Service\ParcelShopsService')
        ->getParcelShopCollection();
    

    Returns an array of \Answear\GlsBundle\Response\DTO\ParcelShop objects.


Implementation Patterns

Core Workflows

  1. Fetching Parcel Shops:

    • Use ParcelShopsService for real-time data:
      $service = $container->get(ParcelShopsService::class);
      $shops = $service->getParcelShopCollection();
      
    • Cache results (e.g., with Symfony Cache component) to reduce API calls:
      $cacheKey = 'gls_shops_' . implode('_', $service->getCountryCodes());
      $shops = $cache->get($cacheKey, function() use ($service) {
          return $service->getParcelShopCollection();
      });
      
  2. Filtering Shops:

    • Filter by features (e.g., FeatureEnum::PACKAGES):
      $filtered = array_filter($shops, fn(ParcelShop $shop) =>
          $shop->getFeatures()->contains(FeatureEnum::PACKAGES)
      );
      
    • Filter by opening hours (e.g., Monday 9 AM–5 PM):
      $monday = $shops[0]->getOpenings()->getMonday();
      if ($monday->isOpen()) {
          // Logic for open shops
      }
      
  3. Error Handling:

    • Wrap API calls in a try-catch:
      try {
          $shops = $service->getParcelShopCollection();
      } catch (ServiceUnavailableException $e) {
          $this->logger->error('GLS API unavailable', ['exception' => $e]);
          // Fallback: Return cached data or empty array
      }
      

Integration Tips

  • Symfony Forms: Bind ParcelShop DTOs to form fields for user selection:
    $builder->add('parcelShop', EntityType::class, [
        'class' => ParcelShop::class,
        'choice_label' => 'name',
        'choice_value' => 'id',
    ]);
    
  • API Rate Limiting: Use Guzzle middleware to enforce retries:
    $client = new Client([
        'handler' => HandlerStack::create([
            new RetryMiddleware([
                'max_retries' => 3,
                'delay' => 100,
            ]),
        ]),
    ]);
    
  • Testing: Mock ParcelShopsService in unit tests:
    $this->mockBuilder()
        ->getMockBuilder(ParcelShopsService::class)
        ->disableOriginalConstructor()
        ->onlyMethods(['getParcelShopCollection'])
        ->getMock();
    

Gotchas and Tips

Pitfalls

  1. Country Code Validation:

    • The bundle does not validate countryCode in config. Invalid codes (e.g., US) will cause silent failures. Validate manually:
      $validCountries = ['HU', 'SK', 'CZ', 'RO', 'SI', 'HR'];
      if (!preg_match('/^('.implode('|', $validCountries).')(\|'.implode('|', $validCountries).')*$/', $config['countryCode'])) {
          throw new \InvalidArgumentException('Invalid country codes');
      }
      
  2. API Endpoint Changes:

    • Version 3.0.0 changed the GLS API endpoint. Ensure your tests account for this:
      // Test for endpoint changes
      $this->assertStringContainsString('new-endpoint', $service->getClient()->getConfig('base_uri'));
      
  3. Feature Enum Deprecation:

    • MabeEnum was replaced with PHP’s native Enum in 3.0.0. Update type hints:
      // Old (pre-3.0.0)
      $features = $shop->getFeatures(); // Returns MabeEnum
      
      // New (3.0.0+)
      $features = $shop->getFeatures(); // Returns FeatureEnum
      
  4. Null Handling:

    • Fields like iscodhandler may be null. Use null-safe operators:
      $codHandler = $shop->getIsCodHandler() ?? false;
      

Debugging

  • Enable Logging: Configure a custom logger to debug API responses:

    answear_gls:
        logger: app.debug_logger  # Monolog channel
    

    Log the raw response in a custom ParcelShopsService decorator.

  • Guzzle Debugging: Add Guzzle’s debug handler to inspect HTTP traffic:

    $stack = HandlerStack::create();
    $stack->push(Middleware::tap(function (RequestInterface $request) use ($logger) {
        $logger->debug('GLS Request', ['url' => $request->getUri(), 'method' => $request->getMethod()]);
    }));
    

Extension Points

  1. Custom DTOs: Extend ParcelShop to add business logic:

    class ExtendedParcelShop extends ParcelShop {
        public function isOpenNow(): bool {
            $now = new \DateTime();
            $today = $this->getOpenings()->getDay($now->format('N'));
            return $today->isOpen() && $today->isOpenAt($now);
        }
    }
    
  2. Override API Client: Replace the default Guzzle client in services.yaml:

    services:
        Answear\GlsBundle\Service\ParcelShopsService:
            arguments:
                $client: '@custom_gls_client'  # Your Guzzle client
    
  3. Add New Features: Extend FeatureEnum for custom GLS features:

    enum FeatureEnum {
        case PACKAGES;
        case PARCELS;
        case // Your custom feature
        case CUSTOM_FEATURE;
    }
    

    Update the ParcelShop DTO to include the new feature.

Performance Tips

  • Batch Processing: Process large datasets in chunks to avoid memory issues:
    $batchSize = 100;
    foreach (array_chunk($shops, $batchSize) as $batch) {
        // Process batch
    }
    
  • Lazy Loading: Use generators for iterative access:
    function getParcelShopsGenerator(ParcelShopsService $service): Generator {
        foreach ($service->getParcelShopCollection() as $shop) {
            yield $shop;
        }
    }
    
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