0

I'm using flysystem to work with my files.

I don't see an easy way to flatten a directory so I used this

public function flattenDir($dir, $destination = null) {
  $files = find($dir . '/*');
  foreach ($files as $file) {
       $localdir = dirname($file);

       if (!isDirectory($file)) {
            $destination = $dir . '/' . basename($file);
            move($file, $destination);
       }
       if (isDirectory($localdir) && isEmptyDirectory($localdir) && ($localdir != $dir)) {
            remove($localdir);
       }
  }
}

Is there an easier way by using flysystem?

Atnaize
  • 1,766
  • 5
  • 25
  • 54
  • 2
    By flatten, do you mean move all files out of subdirectories recursively, and then remove the subdirectories? – Ethan May 08 '18 at 13:44
  • Is it working for You? I mean `$move()` ? It seems that flysystem don't provide so "advanced" methods, so You have to write some on Your own, but I'm curious why You don't use flysystem here? – bigwolk May 08 '18 at 13:52
  • @Davіd Yes exactly – Atnaize May 08 '18 at 14:00
  • @Raccoon Your code looks very similar to the code here: https://stackoverflow.com/a/17087268/3088508, but without `$this->`. I suggest you just make it work with regular PHP and post it here, if you don't get any answers using flysystem. – Ethan May 08 '18 at 14:40

1 Answers1

0

I finally used that. It also manage a few things that I needed

I'm using flysystem mount manager but this script could be easily adapted to work with the default flysystem instance.

$elements should be the result of manager->listContents('local://my_dir_to_flatten');

And $root is a string my_dir_to_flatten in my case.

public function flatten($elements , $root) {

    $files = array();
    $directories = array();

    //Make difference between files and directories
    foreach ($elements as $element) {

      if( $element['type'] == 'file' ) {
        array_push($files, $element);
      } else {
        array_push($directories, $element);
      }

    }

    //Manage files
    foreach ($files as $file) {

      //Dont move file already in root
      if($file['dirname'] != $root) {
        //Check if filename already used in root directory
        if (  $this->manager->has('local://'.$root . '/' . $file['basename']) ) {
          //Manage if file don't have extension
          if( isset( $file['extension']) ) {
            $file['basename'] = $file['filename'] . uniqid() . '.' . $file['extension'];
          } else {
            $file['basename'] = $file['filename'] . uniqid();
          }
        }

        //Move the file
        $this->manager->move('local://' . $file['path'] , 'local_process://' . $root . '/' . $file['basename']);
      }

    }

    //Delete folders
    foreach ($not_files as $file) {
      $this->manager->deleteDir( 'local://' . $file['path'] );
    }
  }
Atnaize
  • 1,766
  • 5
  • 25
  • 54