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

Relay Blob Library Laravel Package

dbp/relay-blob-library

PHP helper library for interacting with dbp relay-blob-bundle. Provides BlobApi for HTTP mode with optional OIDC authentication to add, fetch, and remove files (blobs) in a bucket, using simple BlobFile objects and identifiers.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require dbp/relay-blob-library
    

    Ensure your Laravel project meets the PHP version requirements (≥8.2).

  2. First Use Case: Upload a file via HTTP mode with OIDC authentication:

    use Dbp\Relay\BlobLibrary\Api\BlobApi;
    
    $blobApi = BlobApi::createHttpModeApi(
        'my-bucket',
        'my-bucket-key',
        'https://blob.example.com',
        true,
        'https://oidc-provider.example.com',
        'client-id',
        'client-secret'
    );
    
    $blobFile = new \Dbp\Relay\BlobLibrary\Api\BlobFile();
    $blobFile->setFilename('example.txt');
    $blobFile->setFile(new \SplFileInfo(storage_path('app/example.txt')));
    $blobFile->setPrefix('my-prefix');
    
    $uploadedFile = $blobApi->addFile($blobFile);
    
  3. Key Files:

    • Review examples/BlobApiExamples.php for practical usage.
    • Check src/Api/BlobApi.php for core methods.

Implementation Patterns

Core Workflows

  1. File Operations:

    • Upload: Use addFile() with BlobFile objects (supports SplFileInfo, StreamInterface, or strings).
    • Download: Fetch via getFile($identifier) or stream with getFileStream($identifier).
    • Delete: Use deleteFileByIdentifier($identifier) or deleteFilesByPrefix($prefix).
  2. Authentication:

    • OIDC: Configure via createHttpModeApi() with OIDC provider URL and credentials.
    • OAuth2: Use setOAuth2Token() for token-based auth (e.g., for refresh flows).
  3. Signed URLs:

    • Generate time-limited URLs for secure file access:
      $signedUrl = $blobApi->createSignedUrl($identifier, 3600); // 1-hour expiry
      
  4. Metadata Handling:

    • Set custom metadata (e.g., setMetadata(['key' => 'value'])).
    • Retrieve metadata via getFileMetadata($identifier).

Integration Tips

  • Service Container: Bind the library to Laravel’s container for dependency injection:

    $this->app->singleton(\Dbp\Relay\BlobLibrary\Api\BlobApiInterface::class, function ($app) {
        return BlobApi::createHttpModeApi(
            config('blob.bucket'),
            config('blob.key'),
            config('blob.base_url'),
            config('blob.oidc.enabled'),
            config('blob.oidc.provider_url'),
            config('blob.oidc.client_id'),
            config('blob.oidc.client_secret')
        );
    });
    
  • Form Requests: For file uploads via HTTP requests, use multipart/form-data with the BlobFile object:

    $request->file('file')->storeAs('temp', 'upload.tmp');
    $blobFile = new BlobFile();
    $blobFile->setFilename($request->file('file')->getClientOriginalName());
    $blobFile->setFile(new SplFileInfo(storage_path("temp/upload.tmp")));
    
  • Error Handling: Wrap API calls in try-catch blocks to handle BlobApiError:

    try {
        $blobApi->addFile($blobFile);
    } catch (BlobApiError $e) {
        Log::error('Blob upload failed: ' . $e->getErrorId(), $e->getErrorDetails());
        throw new \Exception('Failed to upload file', 0, $e);
    }
    
  • Batch Operations: Use getFilesByPrefix() to retrieve iterables of files matching a prefix:

    foreach ($blobApi->getFilesByPrefix('my-prefix') as $file) {
        // Process each file
    }
    

Gotchas and Tips

Pitfalls

  1. File Resource Leaks:

    • Always ensure files are closed after operations. The library auto-closes resources, but verify streams are properly handled in custom implementations.
  2. OIDC/OAuth2 Token Management:

    • Tokens expire. Implement a refresh mechanism or use the library’s built-in token handling:
      $blobApi->setOAuth2Token($refreshToken); // Refresh token
      
  3. Content-Type Headers:

    • PATCH requests use application/merge-patch+json. Ensure your API aligns with this (see changelog v0.2.6).
  4. Prefix Handling:

    • Prefixes are case-sensitive. Validate prefixes before operations to avoid silent failures.
  5. PHP API vs HTTP Mode:

    • The library supports both HTTP and direct PHP API modes. Direct mode (via dbp.relay.blob.file_api service) bypasses HTTP overhead but requires the relay-blob-bundle to be installed.

Debugging

  • Error Codes: Use BlobApiError::getErrorId() to map errors to the blob bundle’s error codes. Example:

    if ($e->getErrorId() === BlobApiError::ERROR_ID_INVALID_BLOB_IDENTIFIER) {
        // Handle invalid identifier
    }
    
  • Logging: Enable debug logging for HTTP requests:

    $blobApi->setDebug(true); // Enable debug mode
    
  • Checksums: If checksums (e.g., MD5) are enabled, verify file integrity post-upload. Disable via config if not needed:

    $blobApi->setSendChecksums(false);
    

Extension Points

  1. Custom BlobFileApi: Implement BlobFileApiInterface for non-HTTP backends (e.g., S3, local storage):

    class CustomBlobApi implements BlobFileApiInterface {
        public function addFile(BlobFile $blobFile): BlobFile { /* ... */ }
        // Implement other required methods
    }
    
  2. Signature Verification: Use SignatureTools::verify() to validate signed URLs or responses:

    $isValid = SignatureTools::verify($signedUrl, $expectedPayload);
    
  3. Configuration: Override defaults via Symfony’s config system (if integrated). Example:

    # config/packages/blob.yaml
    dbp_relay_blob_library:
        http:
            timeout: 30
            max_retries: 3
    
  4. Testing: Use the provided test utilities (e.g., BlobApiTestCase) to mock API responses:

    use Dbp\Relay\BlobLibrary\Tests\BlobApiTestCase;
    
    class MyTest extends BlobApiTestCase {
        protected function setUp(): void {
            $this->mockApiResponse(200, ['identifier' => 'test']);
        }
    }
    

Configuration Quirks

  • Delete Timing: The deleteIn parameter (formerly retentionDuration) uses ISO 8601 strings for scheduling deletions. Example:

    $blobFile->setDeleteIn('PT1H'); // Delete after 1 hour
    
  • File Types: The library restricts file inputs to string, StreamInterface, or SplFileInfo. Avoid passing raw resources directly.

  • Symfony Integration: The bundle integration is "soon to come," but you can manually bind services to Laravel’s container (see Implementation Patterns).

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.
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
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui