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

Hubic Api Bundle Laravel Package

ckrupa/hubic-api-bundle

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Install Dependencies**:
   ```bash
   composer require ckrupa/hubic-api-bundle:dev-master hwi/oauth-bundle sensio/buzz-bundle

Ensure HWIOAuthBundle and SensioBuzzBundle are registered in AppKernel.php.

  1. Configure HWIOAuthBundle: Follow the sample config for Hubic OAuth. Key steps:

    • Add hubic resource in hwi_oauth.resource_owners.
    • Configure hubic in hwi_oauth.connect with client ID/secret (register at hubic.com).
    • Set hwi_oauth.failure_path (e.g., /login).
  2. First API Call: Inject the service and verify login:

    use Symfony\Component\DependencyInjection\ContainerInterface;
    
    class MyController {
        private $hubicApi;
    
        public function __construct(ContainerInterface $container) {
            $this->hubicApi = $container->get('ckrupa_hubic_api');
        }
    
        public function checkLogin() {
            if (!$this->hubicApi->isLoggedIn()) {
                throw new \RuntimeException('Invalid OAuth token!');
            }
            return $this->hubicApi->send('/account/credentials');
        }
    }
    

First Use Case: Upload a File

// Upload a file to root directory
$response = $this->hubicApi->send(
    '/files',
    'POST',
    [
        'file' => new \Symfony\Component\HttpFoundation\File\UploadedFile(
            '/path/to/local/file.txt',
            'file.txt'
        ),
        'parent' => '/', // Root directory
    ]
);

Implementation Patterns

Workflow: OAuth Flow

  1. Login Route: Redirect users to Hubic OAuth:

    // src/Acme/DemoBundle/Controller/DefaultController.php
    public function connectAction() {
        return $this->container->get('hwi_oauth.security.controller')
            ->connectAction('hubic', null, null);
    }
    
  2. Post-OAuth Callback: Handle the callback in hwi_oauth.connect.success_handler (default: hwi_oauth.redirect_handler).

  3. API Integration: Use the service in controllers/services:

    $files = $this->hubicApi->send('/files');
    

Common Patterns

  1. Pagination: Hubic API uses ?limit=N&offset=M. Implement a helper:

    private function getPaginatedFiles(int $page = 1, int $perPage = 20) {
        $offset = ($page - 1) * $perPage;
        return $this->hubicApi->send(
            sprintf('/files?limit=%d&offset=%d', $perPage, $offset)
        );
    }
    
  2. Error Handling: Wrap API calls in a service:

    public function safeSend(string $endpoint, string $method = 'GET', array $data = []) {
        try {
            return $this->hubicApi->send($endpoint, $method, $data);
        } catch (\Exception $e) {
            $this->logger->error(sprintf(
                'Hubic API error [%s]: %s',
                $endpoint,
                $e->getMessage()
            ));
            throw new \RuntimeException('Hubic API request failed.', 0, $e);
        }
    }
    
  3. File Operations:

    • Upload:
      $this->hubicApi->send('/files', 'POST', ['file' => $uploadedFile]);
      
    • Download:
      $fileData = $this->hubicApi->send('/files/{id}/download');
      file_put_contents('local_path', $fileData);
      
    • Delete:
      $this->hubicApi->send('/files/{id}', 'DELETE');
      
  4. Webhooks (Advanced): Use Hubic’s webhook API to trigger Symfony events:

    # config.yml
    hwi_oauth:
        firewall_names: [main]
        connect:
            hubic:
                class: Acme\DemoBundle\Security\HubicUserProvider
                options:
                    webhook_secret: "%hubic_webhook_secret%"
    

Gotchas and Tips

Pitfalls

  1. OAuth Token Expiry:

    • Hubic tokens expire after ~1 hour. Cache the service or implement token refresh:
      if (!$this->hubicApi->isLoggedIn()) {
          $this->container->get('hwi_oauth.security.controller')
              ->connectAction('hubic', null, null);
      }
      
    • Tip: Use hwi_oauth.token_storage to persist tokens in the session.
  2. Rate Limiting:

    • Hubic enforces rate limits. Implement exponential backoff:
      use Symfony\Component\Stopwatch\Stopwatch;
      
      $stopwatch = new Stopwatch();
      $event = $stopwatch->start('hubic_request');
      
      try {
          return $this->hubicApi->send($endpoint);
      } catch (\Symfony\Component\HttpKernel\Exception\HttpException $e) {
          if ($e->getStatusCode() === 429) {
              $event->stop();
              $duration = $event->getDuration();
              sleep(max(1, $duration * 2)); // Exponential backoff
              return $this->hubicApi->send($endpoint);
          }
          throw $e;
      }
      
  3. File Size Limits:

    • Hubic’s API has a 50MB upload limit. For larger files:
      • Use chunked uploads (not natively supported; implement manually).
      • Tip: Store large files locally and upload a symlink to Hubic.
  4. CORS Issues:

    • If using Hubic’s API from a frontend, ensure CORS headers are configured on your Symfony app:
      # config/packages/nelmio_cors.yaml
      nelmio_cors:
          defaults:
              allow_origin: ["*"]
              allow_methods: ["GET", "POST", "PUT", "DELETE"]
              allow_headers: ["Content-Type", "Authorization"]
              expose_headers: []
              max_age: 3600
      
  5. Deprecated HWIOAuthBundle Version:

    • The bundle assumes HWIOAuthBundle v0.3.x. If using v1.x:
      • Update the config to match HWI v1 docs.
      • Tip: Pin hwi/oauth-bundle:^0.3 in composer.json if compatibility is critical.

Debugging

  1. Enable API Debugging:

    • Log raw responses to debug issues:
      $this->hubicApi->setDebug(true);
      $response = $this->hubicApi->send('/account/credentials');
      $this->logger->debug('Hubic API Response:', ['response' => $response]);
      
  2. Common Errors:

    • 401 Unauthorized: Token expired or invalid. Re-authenticate.
    • 403 Forbidden: Insufficient permissions. Check OAuth scopes.
    • 404 Not Found: Invalid endpoint. Verify Hubic’s API docs.
  3. Testing:

    • Use Hubic’s sandbox for testing:
      $this->hubicApi->setBaseUrl('https://api.sandbox.hubic.com');
      

Extension Points

  1. Custom API Wrapper: Extend the service to add domain-specific methods:

    // src/Acme/DemoBundle/Service/HubicService.php
    class HubicService {
        private $hubicApi;
    
        public function __construct(\Ckrupa\HubicApiBundle\Service\HubicApi $hubicApi) {
            $this->hubicApi = $hubicApi;
        }
    
        public function getUserQuota() {
            $credentials = $this->hubicApi->send('/account/credentials');
            return [
                'used' => $credentials['used'],
                'total' => $credentials['quota'],
            ];
        }
    }
    
  2. Event Listeners: Trigger events on API calls:

    // src/Acme/DemoBundle/EventListener/HubicListener.php
    class HubicListener {
        public function onHubicRequest(HubicEvent $event) {
            $this->logger->info(sprintf(
                'Hubic API call: %s %s',
                $event->getMethod(),
                $event->getEndpoint()
            ));
        }
    }
    
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.
craftcms/url-validator
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony