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

Php Symfony Client Laravel Package

api-check/php-symfony-client

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Steps
1. **Installation**: Add the package via Composer:
   ```bash
   composer require api-check/php-symfony-client

The bundle auto-enables via Symfony Flex.

  1. Configuration: Set your API key in .env:

    APICHECK_API_KEY=your_api_key_here
    APICHECK_REFERER=https://yourdomain.com  # Required if API key has "Allowed Hosts"
    

    Or configure via config/packages/apicheck.yaml.

  2. First Use Case: Inject ApiClient into a service and perform a global search (most versatile endpoint):

    use ApiCheck\Api\ApiClient;
    
    class AddressService {
        public function __construct(private ApiClient $apiCheck) {}
    
        public function findAddresses(string $query): array {
            return $this->apiCheck->globalSearch('nl', $query, ['limit' => 5])->Results;
        }
    }
    

    Call it from a controller:

    $results = $this->addressService->findAddresses('Amsterdam');
    

Implementation Patterns

Core Workflows

  1. Address Autocomplete

    • Use globalSearch() with a partial query (e.g., 'Amst') to populate a dropdown.
    • Filter results by type (e.g., city, street) to prioritize relevant matches.
    $results = $this->apiCheck->globalSearch('nl', $userInput, [
        'limit' => 3,
        'city_id' => $preferredCityId  // Optional: Narrow by city
    ]);
    
  2. Address Validation

    • For Netherlands/Luxembourg, use lookup() to validate a full address:
    $address = $this->apiCheck->lookup('nl', [
        'postalcode' => '1012LM',
        'number' => '1'
    ]);
    if ($address->valid) {
        // Proceed with valid address
    }
    
  3. Belgium-Specific Addresses

    • Chain searches: Use searchMunicipality() to get municipality_id, then filter globalSearch():
    $municipalities = $this->apiCheck->searchMunicipality('be', 'Antwerpen');
    $municipalityId = $municipalities->Results[0]->id;
    
    $addresses = $this->apiCheck->globalSearch('be', 'Station', [
        'municipality_id' => $municipalityId
    ]);
    
  4. User Input Sanitization

    • Normalize input (e.g., trim, lowercase) before searching to avoid duplicate API calls:
    $query = strtolower(trim($request->get('query')));
    

Integration Tips

  • Caching: Cache frequent searches (e.g., city lists) with Symfony’s cache system:
    $cache = $this->container->get('cache.app');
    $cities = $cache->get('nl_cities', function() {
        return $this->apiCheck->search('nl', 'city', ['limit' => 1000]);
    });
    
  • Event-Driven Updates: Use Symfony’s KernelEvents::TERMINATE to log API usage or update analytics.
  • Form Integration: Bind results to Symfony Forms for address fields:
    $form->add('street', EntityType::class, [
        'class' => AddressResult::class,
        'choice_label' => 'name',
        'query_builder' => function(AddressRepository $repo) use ($query) {
            return $repo->findBySearch($query);
        }
    ]);
    

Gotchas and Tips

Pitfalls

  1. Rate Limiting

    • The API enforces rate limits (check docs.apicheck.nl). Implement exponential backoff for retries:
    try {
        $result = $this->apiCheck->globalSearch(...);
    } catch (RateLimitException $e) {
        sleep(2 ** $attempt); // Exponential backoff
    }
    

    Tip: Monitor usage via the ApiCheck dashboard.

  2. Country-Specific Quirks

    • Belgium: Localities (locality_id) and municipalities (municipality_id) are critical for precision. Always filter by these IDs when possible.
    • Netherlands: Postal codes are 4 digits + 2 letters (e.g., 1012LM). Validate format before API calls:
      if (!preg_match('/^\d{4}[A-Za-z]{2}$/', $postalCode)) {
          throw new \InvalidArgumentException('Invalid Dutch postal code');
      }
      
  3. ID Mismatches

    • IDs (e.g., city_id, street_id) are country-specific. Reuse IDs across countries only if documented (e.g., Luxembourg shares IDs with Netherlands for some endpoints).
  4. Number Additions

    • For addresses with units (e.g., 1A), use getNumberAdditions() to validate before lookup:
    $additions = $this->apiCheck->getNumberAdditions('nl', '1012LM', '1');
    if (!in_array('A', $additions->numberAdditions)) {
        throw new \RuntimeException('Invalid number addition');
    }
    

Debugging

  • Enable API Debugging: Set APP_DEBUG=true in .env to log API responses:
    # config/packages/apicheck.yaml
    apicheck:
        debug: '%kernel.debug%'
    
  • Validate Responses: Check the meta field in responses for errors:
    if (isset($result->meta->error)) {
        throw new \RuntimeException($result->meta->error->message);
    }
    

Extension Points

  1. Custom Response Mappers

    • Extend the ApiClient to transform responses (e.g., flatten nested objects):
    class CustomApiClient extends ApiClient {
        public function searchWithFlattenedResults(string $country, string $type, array $params) {
            $results = parent::search($country, $type, $params);
            return array_map(function($item) {
                return (array) $item + ['full_name' => "{$item->name} ({$item->type})"];
            }, $results->Results);
        }
    }
    

    Register it as a service override:

    services:
        ApiCheck\Api\ApiClient: '@custom_api_client'
    
  2. Event Listeners

    • Listen for API calls to log usage or transform requests:
    $container->get('api_check.api_client')->addListener(function($event) {
        if ($event->getType() === 'globalSearch') {
            $event->setParams(array_merge($event->getParams(), ['debug' => true]));
        }
    });
    
  3. Symfony Messenger

    • Offload heavy searches to a background job:
    $this->messageDispatcher->dispatch(
        new SearchAddressesMessage($query, $country)
    );
    

    Process with a worker:

    public function __invoke(SearchAddressesMessage $message) {
        return $this->apiCheck->globalSearch($message->country, $message->query);
    }
    

Configuration Quirks

  • Referer Header: If your API key restricts hosts, ensure APICHECK_REFERER matches the request’s Host header. For local development, use:
    APICHECK_REFERER=http://localhost
    
  • Environment Overrides: Use %env(resolve:APICHECK_API_KEY)% in YAML to resolve nested env vars:
    apicheck:
        api_key: '%env(resolve:APP_API_KEYS/apicheck)%'
    

Performance Tips

  • Batch Requests: For bulk operations (e.g., validating 100 addresses), use the ApiCheck batch endpoint (not covered by this bundle) or implement parallel requests with Symfony\Component\Messenger\HandleTrait.
  • Lazy Loading: Load address details only when needed (e.g., defer lookup() until the user selects a result).

```markdown
## Example Debugging Workflow
1. **Symptom**: Global search returns empty results for a known address.
2. **Steps**:
   - Verify the `country` code is correct (e.g., `'nl'` for Netherlands).
   - Check if the `query` is too broad (e.g., `'A'` may return too many results; try `'Amsterdam'`).
   - Enable debug mode (`APP_DEBUG=1`) and inspect the raw API response:
     ```php
     $response = $this->apiCheck->getClient()->get('global-search', [
         'query' => ['country' => 'nl', 'query' => 'Damrak']
     ]);
     file_put_contents('debug.json', $response->getBody());
     ```
   - Confirm
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.
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle
dmstr/api-platform-utils-bundle
dmstr/api-configuration-bundle
chrisdev/ux-components
baks-dev/finances
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle