Search code examples
phpshopware6flysystem

How to proper use Flysystem and Local Adapter


Since I couldn’t find a proper documentation and examples for flysystem, I am asking you for help. Currently I am developing a plugin (for Shopware 6), and I am using some sources that are stored inside my plugin (such as pictures, and csv files).
The structure looks like this

|-- custom
   |-- plugins
       |-- ImporterPlugin
          |-- src
            |-- Adapter
              |-- CsvImportAdapter.php
              |-- ImportAdapterInterface.php
            |-- Command
              |-- ImportCommand.php
            |-- Factory
              |-- AdapterFactory.php
            |-- Resources
            |-- Service
            |-- ImporterPlugin.php
          |-- upload
            |-- product.csv
            |-- media
              |-- Image1.jpg

Inside .env I wrote the file paths that I need

IMPORT_CSV_PATH=/var/www/html/custom/plugins/ImporterPlugin/upload/products.csv
IMPORT_MAP_PATH=/var/www/html/custom/plugins/ImporterPlugin/src/Resources/maps/product.map.json

PRODUCTIMPORTER_MEDIA_SOURCE_PATH=/var/www/html/custom/plugins/ImporterPlugin/upload/media/

My question is, how can I implement Local Adapter (Flysystem)? And where to call functions / methods? The functionality of the plugin is mainly called in command line. Please provide some examples. Thanks


Solution

  • In your services.xml of your plugin you can use the FileSystemFactory and a collection of arguments to define your filesystem abstraction.

    <service class="League\Flysystem\FilesystemInterface" id="importer_plugin.filesystem.private" public="true">
        <factory service="Shopware\Core\Framework\Adapter\Filesystem\FilesystemFactory" method="factory"/>
        <argument type="collection">
            <argument key="type">local</argument>
            <argument key="config" type="collection">
                <argument key="root">%kernel.plugin_dir%/ImporterPlugin/upload</argument>
            </argument>
        </argument>
    </service>
    

    You can then inject importer_plugin.filesystem.private into your other services and work with the filesystem abstraction rooted in the upload directory.

    public function __construct(FilesystemInterface $filesystem)
    {
        $this->filesystem = $filesystem;
    }
    
    // ...
    
    $products = $this->filesystem->read('products.csv');