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/fd7cd47969195ad20002bca4bad7179d to your computer and use it in GitHub Desktop.
Save sutlxwhx/fd7cd47969195ad20002bca4bad7179d to your computer and use it in GitHub Desktop.
Copy specified files to the new directory
<?php
/**
* @author https://gist.github.com/sutlxwhx
*
* @version 0.2
*
* @license Apache License 2.0
*
*/
namespace sutlxwhx;
class Copier
{
/**
* @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;
/**
* Copier constructor.
*
* @param $filename Name of the input file
*/
public function __construct($filename, $level_of_details)
{
$this->filename = $filename;
$this->level = $level_of_details;
if ($this->validate() == true) {
return $this->result = $this->process();
} else {
if ($this->level) {
return $this->result = "I was unable to validate your input file or desired output folder. Check if this script has neccessary writing permissions and your input file exists." . PHP_EOL;
} else {
return $this->result = false;
}
}
}
/**
* Check if this script has necessary writing permissions
* Check if the necessary file and folder exists
*/
private function validate()
{
if (!is_writable($this->current_folder)) {
return false;
}
if (file_exists($this->current_folder . $this->filename)) {
return true;
} else {
return false;
}
}
/**
* Specify the copy process
*/
private function process()
{
$current = file($this->current_folder . $this->filename);
foreach ($current as $file) {
$file_data = explode(',', $file);
$current_file = trim($file_data[0]);
$new_folder = trim($file_data[1]);
$new_folder = $this->current_folder . $new_folder . DIRECTORY_SEPARATOR;
if (!file_exists($new_folder)) {
mkdir($new_folder, 0755, true);
}
$desired = $new_folder . $current_file;
if (!file_exists($current_file)) {
if ($this->level) {
print "$current_file is missing!" . PHP_EOL;
}
continue;
}
copy($this->current_folder . $current_file, $desired);
}
if ($this->level) {
print "Copying process is complete." . PHP_EOL;
}
return true;
}
}
/**
* State the name of the list of your files and the name of the directory where you want to put them
* In your input.txt you need to use *.csv format
*
* Each file must start with a new line and data field must be separated with a comma, for example:
* aaa.txt,directory1
* bbb.dat,directory2
* ...
* n.php,directoryn
*
* The directory must be in the current folder where you run this script
*/
/* $copier_worker = new Copier('test.txt', false); */
/* var_dump($copier_worker->result); */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment