Last active
October 27, 2017 18:10
-
-
Save notian/1c347d169e8ffe68ca78cbf108156b40 to your computer and use it in GitHub Desktop.
Directory / File reader using generators
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class FileReader | |
{ | |
private $filenames; | |
public function __construct($input) | |
{ | |
if (is_file($input)) { | |
$this->filenames = [ $input ]; | |
} elseif (is_dir($input)) { | |
$this->filenames = new \DirectoryIterator($input); | |
}elseif( $input instanceof \DirectoryIterator ){ | |
$this->filenames = $input; | |
}elseif( is_array( $input )){ | |
$this->filenames = array_filter($input, function($value){ | |
return is_file( $value ); | |
}); | |
} | |
if (empty($this->filenames)) { | |
throw new NoFileSelectedException('The file or directory not exists'); | |
} | |
} | |
public function filenames() | |
{ | |
foreach( $this->filenames as $file ){ | |
if( $file instanceof \DirectoryIterator ){ | |
if (!$file->isDot() && $file->isReadable()) { | |
yield $file->getFilename(); | |
} | |
}else{ | |
yield $file; | |
} | |
} | |
} | |
public function fp() | |
{ | |
$fp = null; | |
foreach($this->filenames() as $file ){ | |
$fp = fopen($file,'rb' ); | |
do{ | |
yield $fp; | |
}while(!feof($fp)); | |
fclose($fp); | |
} | |
} | |
public function by_entire() | |
{ | |
foreach ($this->filenames() as $filename) { | |
yield file_get_contents($filename); | |
} | |
} | |
public function by_chunk($size = 10000) | |
{ | |
foreach($this->fp() as $fp){ | |
yield fread( $fp, $size); | |
} | |
} | |
public function by_line() | |
{ | |
foreach($this->fp() as $fp ){ | |
yield trim( fgets($fp), "\n" ); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment