Created
March 18, 2009 17:39
-
-
Save mheap/81274 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
## PHP Version of osfameron's fixed width table parser | |
## http://github.com/osfameron/misc-opensource/tree/7317cbb59edb0ec9a5e023049d7c6b423d453d7f/parse-table | |
class row{ | |
private $_cols = array(); | |
private $_parsed = array(); | |
private $_params = array(); | |
private function __get($name){ | |
if (!isset($this->_parsed[$name])){ | |
throw new dataMissingException(); | |
} | |
return $this->get($name); | |
} | |
public function setParam($type, $val){ | |
$this->_params[$type] = $val; | |
} | |
public function addCol($name, array $range, $type){ | |
if ($range[0] > $range[1]){ throw new invalidRangeException(); } | |
// Make substr mirror other implementations | |
$range[1] = $range[1] - $range[0]; | |
$this->_cols[$name] = array($range, $type) ; | |
} | |
public function parse($str){ | |
foreach ($this->_cols as $name => $details){ | |
$range = $details[0]; $type= $details[1]; | |
$val = substr($str, $range[0], $range[1]); | |
if ($this->checkType($val) != $type){ throw new invalidTypeException(); } | |
$this->_parsed[$name]['val'] = $val; | |
$this->_parsed[$name]['type'] = $type; | |
} | |
} | |
public function get($key){ | |
return $this->_parsed[$key]['val']; | |
} | |
public function type($key){ | |
return $this->_parsed[$key]['type']; | |
} | |
private function checkType($str){ | |
$d = date($this->_params['dateformat'], strtotime($str)); | |
if ($d == $str){ return "date"; } | |
if (is_numeric($str)){ return "numeric"; } | |
if ( ($str == 'true') || ($str == 'false') ){ return "boolean"; } | |
return "string"; | |
} | |
} | |
// Initialise the object | |
$r = new row(); | |
// Set Date Format | |
$r->setParam("dateformat", "d-m-Y"); | |
// Add column boundaries and types | |
$r->addCol('first', array(0,7), "string"); | |
$r->addCol('last', array(8,12), "string"); | |
$r->addCol('date', array(13,23), "date"); | |
$r->parse("Michael Heap 18-03-2009"); | |
// Lets's see what comes out | |
echo $r->first; # Michael | |
echo $r->get('first'); # Michael | |
echo $r->last; # Heap | |
echo $r->get('last'); # Heap | |
echo $r->get('date'); # 18-03-2009 | |
echo $r->date .' | '.$r->type('date'); # 18-03-2009 | date | |
echo $r->nothere; # Fatal error: Class 'dataMissingException' not found (Exceptions Need Creating) | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment