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

Cfm Soap Symfony Bundle Laravel Package

cm2tech/cfm-soap-symfony-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require cm2tech/cfm-soap-symfony-bundle
    

    Ensure your composer.json includes the package under require.

  2. Configuration Add the bundle to config/bundles.php:

    return [
        // ...
        Cfm\SoapSymfonyBundle\CfmSoapSymfonyBundle::class => ['all' => true],
    ];
    
  3. First Use Case: Fetch Doctor Data Inject the DoctorDataRequest service into a controller or service:

    use Cfm\SoapSymfonyBundle\Service\DoctorDataRequest;
    use Cfm\SoapSymfonyBundle\Request\DoctorData;
    
    class DoctorController extends AbstractController
    {
        public function __construct(
            private DoctorDataRequest $doctorDataRequest
        ) {}
    
        public function search(DoctorData $doctorData): JsonResponse
        {
            $response = $this->doctorDataRequest->Consultar(
                $doctorData,
                '%env(CFM_API_KEY)%' // Replace with your actual key
            );
            return $this->json($response);
        }
    }
    
  4. Environment Setup Add your CFM API key to .env:

    CFM_API_KEY=your_api_key_here
    

Implementation Patterns

Workflow: SOAP Request Handling

  1. Request Construction Use DoctorData DTO to structure input:

    $doctorData = new DoctorData('SP', 123456); // UF, CRM
    
  2. Service Injection Prefer dependency injection over direct instantiation for testability:

    // services.yaml
    services:
        App\Service\DoctorService:
            arguments:
                $doctorDataRequest: '@cfm_soap_symfony.doctor_data_request'
    
  3. Response Handling Parse raw SOAP responses into domain objects:

    $rawResponse = $doctorDataRequest->Consultar($doctorData, $apiKey);
    $doctor = new Doctor(
        $rawResponse['nome'],
        $rawResponse['especialidades'],
        // ...
    );
    
  4. Error Handling Wrap SOAP calls in try-catch blocks:

    try {
        $response = $doctorDataRequest->Consultar($doctorData, $apiKey);
    } catch (\SoapFault $e) {
        $this->addFlash('error', 'CFM API Error: ' . $e->getMessage());
        return $this->redirectToRoute('home');
    }
    

Integration Tips

  • Caching: Cache frequent SOAP responses (e.g., using Symfony Cache component):

    $cache = $this->get('cache.app');
    $cacheKey = 'cfm_doctor_' . $doctorData->getCrm();
    if (!$cached = $cache->get($cacheKey)) {
        $cached = $doctorDataRequest->Consultar($doctorData, $apiKey);
        $cache->set($cacheKey, $cached, 3600); // Cache for 1 hour
    }
    
  • Rate Limiting: Implement a decorator pattern to throttle requests:

    class ThrottledDoctorDataRequest implements DoctorDataRequestInterface
    {
        public function __construct(
            private DoctorDataRequest $decorated,
            private RateLimiterInterface $limiter
        ) {}
    
        public function Consultar(DoctorData $data, string $apiKey)
        {
            $this->limiter->consume('cfm_api');
            return $this->decorated->Consultar($data, $apiKey);
        }
    }
    
  • Logging: Log SOAP requests/responses for debugging:

    use Psr\Log\LoggerInterface;
    
    $logger->info('CFM SOAP Request', [
        'data' => $doctorData->toArray(),
        'response' => $response,
    ]);
    

Gotchas and Tips

Pitfalls

  1. SOAP Faults

    • Issue: CFM’s SOAP service may return cryptic faults (e.g., SOAP-ENV:Client).
    • Fix: Use try-catch and map faults to user-friendly messages:
      catch (\SoapFault $e) {
          if (strpos($e->getMessage(), 'Invalid CRM') !== false) {
              throw new \InvalidArgumentException('CRM not found');
          }
      }
      
  2. API Key Exposure

    • Issue: Hardcoding keys in controllers violates security best practices.
    • Fix: Use Symfony’s %env() or parameter bags:
      # config/packages/cfm_soap.yaml
      cfm_soap_symfony:
          api_key: '%env(CFM_API_KEY)%'
      
  3. UTF-8 Encoding

    • Issue: Responses may contain non-UTF-8 characters (e.g., á instead of á).
    • Fix: Normalize responses:
      $response = mb_convert_encoding($rawResponse, 'UTF-8', 'ISO-8859-1');
      
  4. WSDL Caching

    • Issue: Symfony’s SOAP client may cache WSDL incorrectly.
    • Fix: Disable caching or clear cache on WSDL changes:
      $client = new \SoapClient($wsdl, [
          'cache_wsdl' => WSDL_CACHE_NONE,
      ]);
      

Debugging Tips

  1. Enable SOAP Traces Configure the SOAP client to log raw requests/responses:

    $client = new \SoapClient($wsdl, [
        'trace' => 1,
        'exceptions' => true,
    ]);
    $request = $client->__getLastRequest();
    $response = $client->__getLastResponse();
    
  2. Validate Input Use Symfony’s Validator to validate DoctorData:

    # config/validator/validation.yaml
    Cfm\SoapSymfonyBundle\Request\DoctorData:
        constraints:
            - All:
                - Cfm\SoapSymfonyBundle\Validator\Constraints\ValidUF
                - Cfm\SoapSymfonyBundle\Validator\Constraints\ValidCRM
    
  3. Mock SOAP for Tests Use php-soap-mock or create a test double:

    $this->createMock(\SoapClient::class)
         ->method('Consultar')
         ->willReturn(['nome' => 'Test Doctor']);
    

Extension Points

  1. Custom Requests Extend the bundle to support additional CFM endpoints (e.g., ConsultarEspecialidades):

    class EspecialidadeDataRequest
    {
        public function ConsultarEspecialidades(string $uf, string $apiKey)
        {
            $client = new \SoapClient($wsdl);
            return $client->ConsultarEspecialidades(['uf' => $uf], ['apiKey' => $apiKey]);
        }
    }
    
  2. Event Dispatching Trigger events for SOAP responses:

    use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
    
    $dispatcher->dispatch(new CfmSoapResponseEvent($response));
    
  3. Async Processing Offload SOAP calls to a message queue (e.g., Symfony Messenger):

    $message = new CfmSoapMessage($doctorData, $apiKey);
    $bus->dispatch($message);
    
  4. Dockerized SOAP For local development, mock the SOAP service with a Docker container:

    # Dockerfile
    FROM php:cli
    RUN pecl install soap
    COPY soap_mock.php /usr/local/bin/soap_mock
    
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
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