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

Gaufrette Browser Bundle Laravel Package

digitalkaoz/gaufrette-browser-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require digitalkaoz/gaufrette-browser-bundle
    

    Register the bundle in config/bundles.php (Symfony 4+):

    return [
        // ...
        Digitalkaoz\GaufretteBrowserBundle\DigitalkaozGaufretteBrowserBundle::class => ['all' => true],
    ];
    
  2. Configure Gaufrette Ensure you have a Gaufrette filesystem configured (e.g., in config/packages/gaufrette.yaml):

    gaufrette:
        filesystems:
            my_filesystem:
                adapter: local
                options:
                    directory: '%kernel.project_dir%/var/files'
    
  3. First Use Case: Basic File Browsing Inject the GaufretteBrowser service into a controller or service:

    use Digitalkaoz\GaufretteBrowserBundle\GaufretteBrowser;
    
    class FileController extends AbstractController
    {
        public function browse(GaufretteBrowser $browser)
        {
            $files = $browser->getFilesystem('my_filesystem')->getFiles();
            // Render files in a template (e.g., Twig)
        }
    }
    
  4. Template Integration Use Twig to iterate over files:

    {% for file in files %}
        <a href="{{ path('file_download', {'id': file.name}) }}">{{ file.name }}</a>
    {% endfor %}
    

Implementation Patterns

Core Workflows

  1. File Listing and Navigation

    • Use getFilesystem() to access a configured filesystem.
    • Chain methods like getFiles(), getDirectories(), or getDirectory() to traverse the filesystem:
      $files = $browser->getFilesystem('my_filesystem')->getDirectory('/subfolder')->getFiles();
      
  2. File Metadata Handling

    • Retrieve file metadata (e.g., size, mtime) via getMetadata():
      $metadata = $browser->getFilesystem('my_filesystem')->getMetadata('file.txt');
      
  3. Integration with Doctrine-like ORM

    • The bundle mimics Doctrine’s ObjectRepository pattern. Extend Digitalkaoz\GaufretteBrowserBundle\Entity\File to add custom logic:
      class CustomFile extends File
      {
          public function getHumanReadableSize()
          {
              return $this->getSize() ? size_format($this->getSize()) : '0B';
          }
      }
      
  4. Symfony Forms for Uploads

    • Use GaufretteBrowser with Symfony’s File type in forms:
      $builder->add('file', FileType::class, [
          'mapped' => false,
          'required' => false,
      ]);
      
    • Save uploaded files via Gaufrette:
      $filesystem = $browser->getFilesystem('my_filesystem');
      $filesystem->write('uploads/' . $file->getClientOriginalName(), file_get_contents($file->getPathname()));
      
  5. Event Listeners for File Operations

    • Dispatch events (e.g., file.pre_upload, file.post_delete) using Symfony’s event dispatcher:
      $dispatcher->dispatch(new FileEvent($file), 'file.pre_upload');
      

Integration Tips

  1. Twig Extensions Create a custom Twig extension to expose GaufretteBrowser methods:

    class GaufretteExtension extends \Twig_Extension
    {
        public function getFunctions()
        {
            return [
                new \Twig_SimpleFunction('list_files', [$this->browser, 'getFiles']),
            ];
        }
    }
    

    Register it in services.yaml:

    services:
        app.twig.gaufrette_extension:
            class: App\Twig\GaufretteExtension
            arguments: ['@digitalkaoz_gaufrette_browser']
            tags: ['twig.extension']
    
  2. API Endpoints Build RESTful endpoints for file operations:

    // src/Controller/FileApiController.php
    class FileApiController extends AbstractController
    {
        public function listFiles(GaufretteBrowser $browser, Request $request)
        {
            $filesystem = $browser->getFilesystem('my_filesystem');
            $path = $request->query->get('path', '/');
            $files = $filesystem->getDirectory($path)->getFiles();
    
            return $this->json(array_map(function ($file) {
                return [
                    'name' => $file->getKey(),
                    'size' => $file->getSize(),
                    'url' => $this->generateUrl('file_download', ['id' => $file->getKey()]),
                ];
            }, $files));
        }
    }
    
  3. Security

    • Restrict access to sensitive directories using Symfony’s voters or ACLs:
      // src/Voter/FileVoter.php
      class FileVoter extends Voter
      {
          protected function supports(string $attribute, $subject): bool
          {
              return $attribute === 'access' && $subject instanceof File;
          }
      
          protected function voteOnAttribute(string $attribute, $subject, TokenInterface $token): bool
          {
              return $token->getUser()->canAccessFile($subject->getKey());
          }
      }
      

Gotchas and Tips

Pitfalls

  1. Deprecated Symfony Versions

    • The bundle was last updated in 2014 and may not support modern Symfony (5.4+/6.x). Test thoroughly or fork the package.
    • Workaround: Use a compatibility layer or replace with api-platform/gaufrette for newer Symfony.
  2. Gaufrette Filesystem Configuration

    • Ensure your gaufrette.yaml is correctly configured. Missing adapters (e.g., local, s3) will throw exceptions.
    • Debug Tip: Dump the filesystem adapter:
      $adapter = $browser->getFilesystem('my_filesystem')->getAdapter();
      var_dump(get_class($adapter));
      
  3. Entity Mapping Quirks

    • The bundle assumes a File entity class. If you extend it, ensure the parent class (Digitalkaoz\GaufretteBrowserBundle\Entity\File) is autoloaded.
    • Fix: Add the bundle’s Entity directory to your autoloader in composer.json:
      "autoload": {
          "psr-4": {
              "Digitalkaoz\\GaufretteBrowserBundle\\": "vendor/digitalkaoz/gaufrette-browser-bundle/src"
          }
      }
      
  4. Performance with Large Directories

    • getFiles() loads all files into memory. For large directories, use pagination or lazy loading:
      $directory = $browser->getFilesystem('my_filesystem')->getDirectory('/large-folder');
      $files = iterator_to_array($directory->getFiles(), false); // Lazy iteration
      
  5. Caching Metadata

    • File metadata (e.g., mtime, size) is fetched on every call. Cache results in a service:
      $cache = $this->container->get('cache.app');
      $metadata = $cache->get('file_metadata:' . $fileKey, function () use ($browser, $fileKey) {
          return $browser->getFilesystem('my_filesystem')->getMetadata($fileKey);
      });
      

Debugging Tips

  1. Enable Gaufrette Debugging Add this to config/packages/dev/gaufrette.yaml:

    gaufrette:
        debug: true
    

    Logs filesystem operations to var/log/dev.log.

  2. Check Filesystem Permissions

    • If files aren’t readable/writable, verify:
      • Directory permissions (chmod -R 755 var/files).
      • User permissions (e.g., www-data for web servers).
  3. Validate File Keys

    • Gaufrette uses forward slashes (/) as path separators, even on Windows. Avoid backslashes (\) in file keys.
  4. Symfony Profiler Integration

    • Dump the GaufretteBrowser service in the profiler to inspect active filesystems:
      $this->container->get('debug.stopwatch')->checkPoint('gaufrette_browser');
      

Extension Points

  1. Custom File Entity Override the default File entity to add fields (e.g., owner, tags):

    namespace App\Entity;
    
    use Digitalkaoz\GaufretteBrowserBundle\Entity\File as BaseFile;
    
    class File extends BaseFile
    {
        private $owner;
        private $tags = [];
    
        // Add getters/setters and Doctrine annotations
    }
    

    Register it in services.yaml:

    digitalkaoz_gaufrette_browser.file.entity.class: App\Entity\File
    
  2. Event Subscribers Listen to

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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware