Skip to content

Instantly share code, notes, and snippets.

@mbischof
Created November 4, 2015 02:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbischof/0b131022bf5c2cd17dfa to your computer and use it in GitHub Desktop.
Save mbischof/0b131022bf5c2cd17dfa to your computer and use it in GitHub Desktop.
abstract class Awk extends CComponent
{
public $filename;
public $fieldSeparator = ';';
protected $data = array();
protected $cntRows = 0;
abstract public function rules();
public function begin()
{
}
public function end()
{
}
public function run()
{
$rules = $this->rules();
$this->begin();
$file_handle = fopen($this->filename, "r");
if (!$file_handle) {
die("Can't open file.\n");
}
while (!feof($file_handle)) {
$line = fgets($file_handle);
if ($line) {
$this->cntRows++;
$this->data = explode($this->fieldSeparator, $line);
array_unshift($this->data, $line);
foreach ($rules as $rule) {
call_user_method($rule, $this);
}
}
}
fclose($file_handle);
$this->end();
}
}
class AwkSample01 extends Awk
{
protected $firstnames;
protected $lastnames;
public function rules()
{
return array(
'action1',
'action2'
);
}
public function begin()
{
$this->firstnames = array();
$this->lastnames = array();
}
public function action1()
{
$this->firstnames[] = $this->data[3];
}
public function action2()
{
$this->lastnames[] = $this->data[4];
}
public function end()
{
var_dump($this->firstnames, $this->lastnames);
echo $this->cntRows . PHP_EOL;
}
}
public function actionTest()
{
$component = Yii::createComponent(array(
'class' => 'AwkSample01',
'filename' => 'data/test.csv'
));
$component->run();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment