Skip to content

Instantly share code, notes, and snippets.

@sutlxwhx
Last active August 24, 2018 23:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sutlxwhx/c9bf0b268d4e61d8339682195ae576fe to your computer and use it in GitHub Desktop.
Save sutlxwhx/c9bf0b268d4e61d8339682195ae576fe to your computer and use it in GitHub Desktop.
Rename all files in the current folder according to your list of file names
<?php
/**
* @author https://gist.github.com/sutlxwhx
*
* @version 0.2
*
* @license Apache License 2.0
*
*/
namespace sutlxwhx;
class Renamer
{
/**
* @var string Set the property that will store the result
*/
public $result;
/**
* @var string Set the absolute path to the current folder
*/
private $current_folder = __DIR__ . DIRECTORY_SEPARATOR;
/**
* Renamer constructor.
*
* @param $list_of_current_files Name of the file where all necessary to process files are specified
* @param $list_of_desired_files Name of the file where all new names are specified
*/
public function __construct($list_of_current_files, $list_of_desired_files, $level_of_details)
{
$this->current = $list_of_current_files;
$this->desired = $list_of_desired_files;
$this->level = $level_of_details;
@$this->current_array = file($this->current_folder . $this->current);
@$this->desired_array = file($this->current_folder . $this->desired);
if ($this->validate() == true) {
return $this->result = $this->process();
} else {
return $this->result = "I was unable to validate your current or desired input files. Check if they don't match in the line length or if they even exists.";
}
}
/**
* Check if both files exist
* Check if both files have the same length
*/
private function validate()
{
if (count($this->current_array) == count($this->desired_array)) {
return true;
} else {
return false;
}
}
/**
* Specify the renaming process
*/
private function process()
{
for ($i = 0; $i < count($this->current_array); $i++) {
$current_file = trim($this->current_array[$i]);
$desired_file = trim($this->desired_array[$i]);
if (!file_exists($current_file)) {
if ($this->level) {
print "$current_file is missing!" . PHP_EOL;
}
continue;
}
rename($this->current_folder . $current_file, $this->current_folder . $desired_file);
if ($this->level) {
print "$current_file was renamed." . PHP_EOL;
}
}
if ($this->level) {
print "===" . PHP_EOL . "Renaming process is complete." . PHP_EOL;
}
return true;
}
}
/**
* Initialise Renamer class and set the necessary parameters and level of details
* File must be present in the current directory
* Dump the result element of an object
*/
/* $rename_worker = new Renamer('current.txt', 'desired.txt', false); */
/* var_dump($rename_worker->result); */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment