3v4l.org

run code in 300+ PHP versions simultaneously
<?php namespace FlatFileParser; $definitions = [ ['name' => 'Serial Number', 'length' => 16, 'type' => 'int'], ['name' => 'Language', 'length' => 3, 'type' => 'string'], ['name' => 'Business Name', 'length' => 32, 'type' => 'string'], ['name' => 'Business Code', 'length' => 8, 'type' => 'string'], ['name' => 'Authorization Code', 'length' => 8, 'type' => 'string'], ['name' => 'Timestamp', 'length' => 20, 'type' => 'timestamp'], ]; $writer = new Writer(); $validator = new Validator(); $parser = new Parser(); if(count($argv) != 2){ $writer->write("ERROR: No flat file provided"); } try{ $data = new SplFileObject($argv[1]); if ($data->isFile() && $data->isReadable()) { $lineNumber = 1; while (!$file->eof()) { $line = $file->fgets(); if($validator->isValidLineLength($line)){ $business = convertLineToBusiness($line); $writer->writeBusiness($business); } else{ $writer->write("Line Number: " + $lineNumber + "ERROR: Line to Long"); } $lineNumber ++; } } else{ $writer->write("ERROR: Flat file not readable"); } } catch(Exception $e){ echo "err"; } class Writer{ public function write($text){ echo $text . "\n"; } public function writeBusiness($lineNumber, $business){ write("Line Number: " + $lineNumber); write("Serial Number: " + $business->serialNumber); write("Language: " + $business->language); write("Business Name: " + $business->businessName); write("Business Code: " + $business->businessCode); write("Authorization Code: " + $business->get(authorizationCode)); write("Timestamp: " + $business->timestamp); } } class Validator{ private $validLineLength; public function isValidLineLength($line){ return strlen($line) < $this->validLineLength; } function Validator(){ $this->validLineLength = 0; foreach($definitions as $definition){ $this->validLineLength += $definition->length; } } } class Parser{ public function convertLineToBusiness($line){ $start = 0; $parms = []; foreach($definitions as $definition){ array_push($parms, substr($line, $start, $definition->length)); $start += $definition->length; } return new Business($parms); } } class Business{ public $serialNumber; public $language; public $businessName; public $businessCode; private $authorizationCode; public $timestamp; /** * Getter for some private attributes * @return mixed $attribute */ public function __get($attribute){ if (isset($this->{"_".$attribute})){ return $this->{"_".$attribute}; } else{ return false; } } public function Business($parms){ $this->serialNumber = $parms[1]; $this->language = $parms[2]; $this->businessName = $parms[3]; $this->businessCode = $parms[4]; $this->authorizationCode = $parms[5]; $this->timestamp = $parms[6]; } } ?>

preferences:
43.75 ms | 402 KiB | 5 Q