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

Recherche Entreprises Bundle Laravel Package

aurelbichop/recherche-entreprises-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

  1. Installation Run composer require aurelbichop/recherche-entreprises-bundle in your Symfony 7.3+ project. Verify the bundle is registered in config/bundles.php (automatically added via Composer).

  2. First Use Case Inject EntrepriseSearchClientInterface into a controller/service to fetch enterprise data:

    use AurelBichop\RechercheEntreprisesBundle\Client\EntrepriseSearchClientInterface;
    
    public function search(EntrepriseSearchClientInterface $client) {
        $result = $client->search('carrefour');
        return $this->json($result->results);
    }
    
  3. Key Classes to Explore

    • EntrepriseSearchClientInterface: Core API client (implemented by EntrepriseSearchClient).
    • SearchResult: Paginated response wrapper.
    • Entreprise: Model for enterprise data (includes siren, nomComplet, siege, etc.).
    • Console commands (recherche-entreprise:search) for quick CLI testing.
  4. Quick CLI Test Run php bin/console recherche-entreprise:search "carrefour" to verify connectivity.


Implementation Patterns

Dependency Injection & Services

  • Client Injection: Prefer constructor injection of EntrepriseSearchClientInterface for testability.
    public function __construct(
        private EntrepriseSearchClientInterface $client,
        private LoggerInterface $logger
    ) {}
    
  • Service Layer: Create a dedicated service to encapsulate business logic:
    class EnterpriseService {
        public function __construct(private EntrepriseSearchClientInterface $client) {}
    
        public function getEnterpriseDetails(string $siren): ?Entreprise {
            $this->client->findBySiren($siren);
            // Add validation/logic here
        }
    }
    

Common Workflows

  1. Search by Name/Keyword

    $results = $client->search('startup tech', [
        'page' => 2, // Pagination support
        'per_page' => 50,
    ]);
    
    • Tip: Use results->total to check for more pages.
  2. Fetch by SIREN

    $entreprise = $client->findBySiren('123456789');
    if (!$entreprise) {
        throw new \RuntimeException("SIREN not found");
    }
    
  3. Bulk Operations

    $sirenList = ['12345', '67890', '54321'];
    $data = array_map([$client, 'findBySiren'], $sirenList);
    
  4. Async Processing Use Symfony’s HttpClient directly (via $client->getHttpClient()) for async requests:

    $promises = [];
    foreach ($sirenList as $siren) {
        $promises[] = $client->getHttpClient()->request('GET', "/entreprises/$siren");
    }
    $responses = \Symfony\Contracts\HttpClient\Promise\PromiseUtils::waitAll($promises);
    

Integration with Symfony Ecosystem

  • Forms: Bind Entreprise objects to Symfony forms for admin panels.
  • API Platform: Expose Entreprise as a resource:
    # config/api_platform/resources.yaml
    resources:
        AurelBichop\RechercheEntreprisesBundle\Entity\Entreprise:
            collectionOperations:
                search: { method: 'GET', path: '/entreprises/search/{query}' }
    
  • Messenger: Dispatch events for enterprise data changes:
    $client->search('query')->then(function (SearchResult $result) {
        $bus->dispatch(new EnterpriseSearchCompleted($result));
    });
    

Configuration

Extend the default timeout or add custom headers:

# config/packages/aurelbichop_recherche_entreprises.yaml
aurel_bichop_recherche_entreprises:
    timeout: 15
    headers:
        X-Custom-Header: "value"

Gotchas and Tips

Pitfalls

  1. Rate Limiting

    • The API enforces rate limits. Cache responses aggressively:
      $cache = new \Symfony\Component\Cache\Adapter\FilesystemAdapter();
      $cachedResult = $cache->get('entreprise_' . $siren, function() use ($client, $siren) {
          return $client->findBySiren($siren);
      });
      
  2. SIREN Validation

    • The API returns null for invalid SIRENs. Validate manually:
      if (!preg_match('/^\d{9}$/', $siren)) {
          throw new \InvalidArgumentException("Invalid SIREN format");
      }
      
  3. Pagination Quirks

    • per_page max is 100. Avoid fetching large datasets in one call.
    • Always check $result->total vs. count($result->results) for partial pages.
  4. Deprecation Warnings

    • The bundle is new (v0.1.0). Monitor for breaking changes in future updates.

Debugging

  • Enable API Debugging: Use the official API’s sandbox to test queries.
  • HTTP Client Logs: Enable Symfony’s HTTP client debug:
    $client->getHttpClient()->getEventDispatcher()->addListener(
        'response',
        function (ResponseEvent $event) {
            $this->logger->debug('API Response', ['status' => $event->getResponse()->getStatusCode()]);
        }
    );
    
  • Console Command Errors: Run with -vvv for verbose output:
    php bin/console recherche-entreprise:search "test" -vvv
    

Extension Points

  1. Custom Responses Transform API responses with a decorator:

    class CustomEntrepriseClient implements EntrepriseSearchClientInterface {
        public function __construct(private EntrepriseSearchClientInterface $decorated) {}
    
        public function findBySiren(string $siren): ?Entreprise {
            $entreprise = $this->decorated->findBySiren($siren);
            if ($entreprise) {
                $entreprise->setCustomField('my_data', 'value');
            }
            return $entreprise;
        }
    }
    

    Register as a service with decorates: aurelbichop_recherche_entreprises.client.

  2. Add New Endpoints Extend the client to support unsupported API endpoints:

    class ExtendedEntrepriseClient implements EntrepriseSearchClientInterface {
        public function getEstablishments(string $siren): array {
            $response = $this->httpClient->request('GET', "/entreprises/$siren/etablissements");
            return $this->decodeResponse($response);
        }
    }
    
  3. Event Dispatching Trigger events on search/fetch:

    $client->search('query')->then(function (SearchResult $result) {
        $dispatcher->dispatch(new EnterpriseSearchedEvent($result));
    });
    

Performance Tips

  • Batch Requests: Use the API’s batch endpoint for multiple SIRENs:
    $client->batchSearch(['12345', '67890']);
    
  • Lazy Loading: Load enterprise details on-demand:
    $entreprise = $client->findBySiren($siren);
    $details = $entreprise->getSiege()->getAdresse(); // Lazy-loaded
    

Testing

  • Mock the Client: Use Mockery or PHPUnit’s createMock:
    $mockClient = $this->createMock(EntrepriseSearchClientInterface::class);
    $mockClient->method('search')->willReturn(new SearchResult([new Entreprise()]));
    
  • Test Console Commands: Use Symfony’s CommandTester:
    $command = new SearchEntrepriseCommand($client);
    $commandTester = new CommandTester($command);
    $commandTester->execute(['query' => 'test']);
    $this->assertStringContainsString('Results:', $commandTester->getDisplay());
    
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope