FileManager

The filemanager is a special tool that performs series of processes on files such as reading and writing into writable files, moving files, copying files to other locations, removing files, renaming files and reading folder contents. It can be used to rename the entire contents of a folder. The following are methods that can be called on the FileManager class.

For the purpose of this tutorial we shall be using a text file.

TEST FILE (testfile.txt)
  $filemanager->readFile($keys, $separator); 
     
    USERNAME : Foo 
    PASSWORD : Bar
    EMAIL    : foobar@email.com
    TALL     : true
                                

seturl
This method is used to set the local path where an action is expected to be performed. Some methods do not require this to be done. Example is shown below:

Sample: Initializing FileManager
  $filemanager  = new FileManager();

  $filemanager->setUrl('directory');  // set base directory or path
                                        

getFolders
The getFolders method returns the directories in a predefined path:

Example: getting directories
  $filemanager->setUrl('some_path');  // set base directory
    
  $filemanager->getFolders();  // returns the available directories
                                        

getFiles
The getFiles method returns the files available in a predefined directory or path:

Example: getting file in directories
  $filemanager->setUrl('some_path');  // set base directory
    
  $filemanager->getFiles();  // returns the full path of files available file in directory
  $filemanager->getFiles(false);  // returns only names of files (and extension) in a directory
  $filemanager->getFiles(false, false);  // returns only names of files in a directory without the extension name
                                        

addDir
The addDir method adds a new directory. This may return null if directory cannot be created

Example: creating directories
  $filemanager->addDir('some_path');  // creates a new directory
                                

lastDir
The lastDir method returns the last set directory. This method is useful when handling zip files.

Example: fetch last directory
  $filemanager->setUrl('myurl')
  $filemanager->lastDir();  // myurl
                                    

openFile
This method is used to open a new directory or to create a new file. It can also create a new file to a non-existing writable directory.

Syntax: open directory
  $filemanager->openFile($strict, $url)
    
    
    where: 
        
      $strict : boolean true permits to create a new directory for a url that does not exist.
      $url    : an optional new url or path to be created. 
                If not supplied, openFile uses the default url set.
                If supplied, overides the default set url from setUrl()   
    
                                        

Example 1
  $filemanager->setUrl('somepath');
    
  if( $filemanager->openFile(true) ) {

      //file path opened successfully

  }
                                        
We can also set a url from the openFile() method by supplying the url as the second argument as shown below
Example 2
  if( $filemanager->openFile(true, 'somefile.txt') ) {

      //file path opened successfully

  }
                                        

readFile
The readFile method is used to read a readable file. This method reads a file line by line to fetch supplied keys. Using test file:

Syntax: read file
  $filemanager->readFile($keys, $separator); 
     
    where: 

      $keys : array of keys to be read in given local file
      $separator  : An optional character separator used to separate keys and values. 
                    By default, this is set as colon :. When set as true, 
                    the readFile checks if the key supplied exists within the file and returns
                    a bool of true or false                                     
    
                                        
Example: reading text file
  $filemanager->setUrl('test.txt');

  $read = $filemanager->readFile(['USERNAME', 'PASSWORD']);  

  var_dump($read); // ['USERNAME' => 'Foo', 'PASSWORD' => 'Bar']
    

  $check = $filemanager->readFile('USERNAME', true);  

  var_dump($check); // returns true because USERNAME key exists in testfile 
                                        

readAll
The readAll method is used to read an entire readable file. This method reads a file line by line and stores each key with its respective values. Using test file:

Syntax: read file
  $filemanager->readAll($separator); 
     
    where: 

      $separator  : An optional character separator used to separate keys and values. 
                    By default, this is set as colon :.
                                        
Example: reading text file
  $filemanager->setUrl('test.txt');
    
  $read = $filemanager->readAll();  

  var_dump($read); // ['USERNAME' => 'Foo', 'PASSWORD' => 'Bar', 'EMAIL' => 'foobar@email.com', 'TALL'=>'true']          
                                        

textWrite
The textWrite method write a text into a file using supplied array key-value pairs

Syntax: write into text file
  $filemanager->textWrite([$key => $value], $options); 
     
    where: 

      $key     : line key
      $value   : value of supplied key
      $options : array containing postions of where text should be written. [before, after]
    
                                        
Example: adding a new line with key and value
  $filemanager->setUrl('text.txt');  

  var_dump($filemanager->read('AGE'));  //returns: false

  $filemanager->textWrite(['AGE' => '30']);  //write AGE to a new line 
    
  $filemanager->textWrite(['AGE' => '30'], ['after' => 'USERNAME']);  //write AGE to a position after USERNAME, else write to a new line 

  $filemanager->textWrite(['AGE' => '30'], ['before' => 'USERNAME']); //write AGE to a position before USERNAME, else write to a new line 

  var_dump($filemanager->read('AGE'));  //returns: ['AGE' => '30']
                                        

textLine
The textLine method writes a new line into a writable file. Example is shown below:

Syntax: adding a new line to writable file
  $filemanager->textLine($number, $options); 
     
    where: 

      $number : number of lines to be added
      $options: array containing postions of where line should be written [before, after]
    
                                        
Example: adding new lines
  $filemanager->textLine(4, ['after'=>'USERNAME']);  //add four new lines after USERNAME line
                                        

textReplace
The method replaces a key's value with a new value. If such key does not exists nothing is written into the file.

Syntax: adding a new line to writable file
  $filemanager->textReplace([$key => $value], $separator); 
     
    where: 

      $key   : target key
      $value : target key's new value.
      $separator : An optional character separator used to separate keys and values. 
                    By default, this is set as colon :. When set as true, 
                    the readFile checks if the key supplied exists within the file and returns
                    a bool of true or false        
                                            
                                        
Example: replacing values
  $filemanager->textReplace(['USERNAME'=>'NewFoo']);  //replaces foo with NewFoo 
  
  //Note:: This can be done for multiple keys.                           
                                        

textUpdate
The method updates a key's value with a new value. If such key does not exists, the values supplied is written to a new line.

Syntax: adding a new line to writable file
  $filemanager->textUpdate([$key => $value], $updates, $separator); 
     
    where: 

        $key   : target key
        $value : target key's new value
        $updates : a referenced variable that contains all successful updates 
        $separator : An optional character separator used to separate keys and values. 
                    By default, this is set as colon :. When set as true, 
                    the readFile checks if the key supplied exists within the file and returns
                    a bool of true or false        
                                            
                                        
Example: replacing values
  $filemanager->textUpdate(['USERNAME'=>'NewFoo'], $updates);  //replaces foo with NewFoo 

  var_dump($updates) // returns: ['USERNAME']

  //Note:: This can be done for multiple keys.                           
                    

textDelete
The method deletes a key and its entire line from the supplied file.

Syntax: adding a new line to writable file
    $filemanager->textDelete($key, $dels, $separator); 
     
    where: 

    $key : target key
    $updates : a referenced variable that contains all successful deletes 
    $separator : An optional character separator used to separate keys and values. 
                By default, this is set as colon :. When set as true, 
                the readFile checks if the key supplied exists within the file and returns
                a bool of true or false
                                        
Example: replacing values
  $filemanager->textReplace(4, ['USERNAME'=>'NewFoo']);  //replaces foo with NewFoo 
  //Note:: This can be done for multiple keys.                           
                                        

load
The load method reads an entire file without instantiating the FileManager class similarly as readAll method. The instantiation is done within itself.

Syntax: load
  FileManager::load($path, $separator);
     
    where: 

      $path : path of file
      $separator  : An optional character separator used to separate keys and values. 
                    By default, this is set as colon :. When set as true, 
                    the readFile checks if the key supplied exists within the file and returns
                    a bool of true or false
    
                                        
Example: loading files
  $contents = FileManager::load('test.txt', ':');   

  var_dump($contents);  //returns the entire array key and value pairs.
                                        

loadenv
The load method reads an entire file just like the load method. All data obtained are saved into the $_ENV global variable.

Syntax: loadenv
  FileManager::loadenv($path, $separator);
     
      where: 

        $path : path of file
        $separator  : An optional character separator used to separate keys and values. 
                    By default, this is set as colon :. When set as true, 
                    the readFile checks if the key supplied exists within the file and returns
                    a bool of true or false
    
                                        
Example
  $contents = FileManager::loadenv('test.txt', ':');   

  var_dump($contents);  //returns the entire array key and value pairs.
                                        

copyTo
This method copies a file from one path to another

Syntax: copyTo
  $filemanager->copyTo($newpath, $newname, $strict);
     
    where: 

      $newpath : newpath of file
      $newname : An optional new file name 
      $strict  : prevents previous errors from stopping operation when handling zip files.
    
                                        
Example
  $filemanager->setUrl('test.txt');   
  $filemanager->copyTo('newdirectory/files', 'newtext.txt', true);  
                                        

moveTo
This method moves a file from one path to another path.

Syntax: moveTo
  $filemanager->copyTo($newpath, $newname, $strict);
     
    where: 

      $newpath : newpath of file
      $newname : An optional new file name 
      $strict  : prevents previous errors from stopping operation when handling zip files.
    
                                        
Example: moveTo
  $filemanager->setUrl('test.txt');   
  $filemanager->moveTo('newdirectory/files', 'newtext.txt', true);  
                                        

move
This method moves a file from one path to another path.

Syntax: move
  $filemanager->move($path1, $path2);
     
    where: 

      $path1  : old path or new destination of folder or file
      $path2  : new destination of folder or file
        
    
                                        
Example: move
  $filemanager->move('somefile.txt', 'newdir/somefile.txt');   moves from one path to another
    
  $filemanager->setUrl('test.txt');  
  $filemanager->move('newdir/test.txt');   moves from predefined path to another
                                        

zipUrl
This method zips a predefined file or folder path.

Syntax: zipUrl
  $filemanager->zipUrl($output);
     
    where: 

      $output : output name of zipfile   
    
                                        
Example: zipUrl
  $filemanager->setUrl('test.txt');    // set a file path
  $filemanager->zip('test.zip');   // zip file to a new name
  $filemanager->move('newdir/test.zip');   // moves zipped file to a new location.
                                        

decompress
This method unzips a zipped file.

Syntax: decompress
  $filemanager->decompress($delete, $strict);
     
    where: 

      $delete  : a boolean of true deletes the compressed file after extraction   
      $strict  : a boolean of true prevent previous errors from stopping code execution   
    
                                        
Example: decompress
  $filemanager->setUrl('test.zip');    // set a file path
  $filemanager->decompress(true);   // decompress file to current location and delete compressed file after
                                        

response
This returns the response obtained when executing operation.

Syntax: response
  $filemanager->response($message);
     
    where: 

      $message  : sets a new message when not supplied, response returns the last set response  
    
                                        
Example: response
  $filemanager->setUrl('test.zip');   // set a file path
  $filemanager->decompress(true);     // decompress file to current location and delete compressed file after
  
  var_dump($filemanager->response()); // returns last response set
                                        

err or error (use err instead)
This returns the error encountered when executing operation. The error method is used when renaming files.

Syntax: err
  $filemanager->response(message);
                                        
Example: response
  $filemanager->setUrl('test.zip'); // set a file path
  $filemanager->decompress(true);   // decompress file to current location and delete compressed file after
  var_dump($filemanager->err());    // returns last error set
                                        

succeeds
This returns a boolean of true if last operation succeeds.

Syntax
  $filemanager->succeeds();
                                        
Example
  $filemanager->setUrl('test.zip'); // set a file path
  $filemanager->decompress(true);   // decompress file to current location and delete compressed file after
  if($filemanager->succeeds()) {

    //file decompressed successfully

  }
                                        

fails
This returns a boolean of true if last operation fails.

Syntax: fails
  $filemanager->fails();
                                        
Example: fails
  $filemanager->setUrl('test.zip');    // set a file path
  $filemanager->decompress(true);   // decompress file to current location and delete compressed file after
  
  if($filemanager->fails()) {

    //file decompressing failed

  }
                                        

source
This function sets the source of a file to be renamed similarly to the setUrl method. However, this must be used to set source path when trying to rename folders or paths.

Syntax: source
  $filemanager->source($path, $extensions);
    
    where:
        
      $path: full path of files to be renamed
      $extensions: the extension of files allowed to be renamed
    
                                        
Example 1 : source
  $fileManager->source(dirname(__FILE__)."/main/images","jpg");
                                        
The setUrl() method can also be used to achieve a similar function by setting its second argument as true just as shown below:
Example 2 : setting source url with setUrl()
  $fileManager->setUrl(dirname(__FILE__)."/main/images", true);
                                        
We can also define the extension by supplying a valid string as shown below
Example 3 : setting source url with setUrl()
  $fileManager->setUrl(dirname(__FILE__)."/main/images", 'jpg');
                                        

rename
This method is used to rename files in a specified a directory. When an extension is supplied, the files renamed will assume the newly specified extension name.

Syntax: rename
  $filemanager->rename($extension);
    
    where:
            
      $extension: optional new file extension name.
                                        
Example: rename
  $filemanager->source(__FILE__."/images", 'jpg'); // set source directory and only select .jpg files 
  $filemanager->rename('png'); // rename selected files in directory to .png extension
                                        

prefix
This method sets the prefix of the files to be renamed. The prefix will be added to the file name during renaming.

Syntax: prefix
  $filemanager->prefix($path, $strict);
    
    where:
        
      $path: full path of files to be renamed
      $strict (optional) : determines if $path must be prepended
    
                                        
Example : prefix
  $filemanager->source(dirname(__FILE__)."/main/images/pexels","jpg"); 
  $filemanager->prefix("list", true); //set a prefix for file names
  $filemanager->rename('png');
                                        

reNumber
The reNumber method directs the FileManger to allow rename() to re-number files in a directory.

Syntax: reNumber
  $filemanager->reNumber($bool);
    
    where:

      $bool  : boolean of false prevents renaming. Default set is true
    
                                        


Example 1 : reNumber
  $filemanager->source(__FILE__."/images", "jpg"); 
  $filemanager->reNumber(); //allow re-numbering of files
  $filemanager->rename(); // renumber all selected files serially
                                        
In the sample above, all the .jpg file extensions will be renamed serially. The serial name will overwrite the default name of each selected file. We can also ensure that a prefix is added when renaming all files. This is shown below:
Example 2 : reNumber
  $filemanager->source(__FILE__."/images", "jpg"); 
  $filemanager->prefix('list'); //add a prefix
  $filemanager->reNumber(); //allow re-numbering of files
  $filemanager->rename(); // renumber all selected files serially
                                        
In the above, each selected file will be renamed serially with a prefix of "list" . Notice that the prefix() method does not need a second argument in this case.

startFrom
The startFrom method defines a numeric point from which the renaming of files should start. For example, if a folder contains 10 jpg images of different names, and each is expected be renamed with a prefix of "list", assuming the startFrom() method is applied, with an integer of 5 ( i.e startFrom(5) ), by default each file is expected to be renamed from list1.jpg - list5.jpg but the application of startFrom(5) will start renaming from integer value 5. Hence, we will have list5.jpg - list15.jpg.

Syntax: startFrom
  $filemanager->startFrom($counter);
    
    where $counter: index from which renaming should be started
    
                                        
Example: startFrom
  $filemanager->source(__FILE__."/images", "jpg"); 
  $filemanager->prefix("list"); // add prefix to file name when renaming (prefix)
  $filemanager->startFrom(5); // start counter from 5
  $filemanager->rename(); // list5.jpg, list6.jpg, ...
                                        

reSpace
The reSpace method directs the FileManager to replace multiple spaces in file names when renaming

Syntax: reSpace
  $filemanager->reSpace($character);
    
    where $character: new character that spaces should be relaced with.
                                    
Example: reSpace
  $filemanager->source(__FILE__."/images", "jpg"); 
  $filemanager->reSpace('_'); // replace whitespace with underscore (_)
  $filemanager->rename(); // list1.jpg, list2.jpg, ...
                                        

smarturl
The smartUrl method directs the FileManager to reduce special characters when renaming files

Syntax: smartUrl
  $filemanager->smartUrl();
                                        
Example: smarUrl
  $filemanager->source(__FILE__."/images", "jpg"); 
  $filemanager->smartUrl('_'); // reduce special characters)
  $filemanager->rename(); // list1.jpg, list2.jpg, ...
                                        

dirFiles
The dirFiles method returns the files within a directory

Syntax: dirFiles
  $filemanager->dirFiles($extensions, $bool);
    
    where:

      $extensions: file extensions to be shown 
      $bool  : boolean of true shows the full path of file when listing files
                                    
Example
  $filemanager->source(__FILE__."/images", "jpg"); 
  $filemanager->dirFiles('jpg'); // return jpg files in a directory
                                        

view
The view() method Resolve renaming to display mode without any active renaming process. It prevents the rename() from actually renaming files. This is used when previewing outputs

Syntax: view
  $filemanager->view(bool);
    
    where:

      bool : boolean of false prevents renaming. Default set is true
    
                                        
Example
  $filemanager->source(__FILE__."/images", "jpg"); 
  $filemanager->view(false); //prevent re-numbering of files
  $filemanager->rename();    //displays expected output