Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $input=file_get_contents ('C:\wamp64\www\naplo.txt','r') or
- exit('Unable to open the file!');
- $fulldiary=new DiaryParser();
- class DiaryRecord
- {
- /**
- * @var \DateTime
- */
- public $date;
- /**
- * @var string
- */
- public $name = '';
- /**
- * @var string[]
- */
- public $attendance = [];
- }
- class DiaryParser
- {
- /**
- * @var int
- */
- protected $year = 2017;
- protected $time='12:00';
- /**
- * @return \DiaryRecord[]
- */
- public function parse(string $diary): array
- {
- $records = [];
- $days = explode('# ', trim($diary, "# \t\r\n"));
- $days = array_filter($days);
- foreach ($days as $day) {
- $lines = $this->splitLines($day);
- $date = $this->parseDateLine(array_shift($lines));
- foreach ($lines as $absenceLine) {
- $absenceLine = $this->parseAbsenceLine($absenceLine);
- $record = new DiaryRecord();
- $record->date = $date;
- $record->name = $absenceLine['name'];
- $record->attendance = $absenceLine['attendance'];
- $records[] = $record;
- }
- }
- return $records;
- }
- protected function splitLines(string $text): array
- {
- return explode("\n",trim($text,"\n"));
- }
- protected function parseDateLine(string $line): string
- {
- $d=explode(" ",trim($line));
- return strval($this->year).'-'.$d[0].'-'.$d[1].' '.($this->time);
- }
- protected function parseAbsenceLine(string $line): array
- {
- return [
- 'name' => mb_substr($line,0,-8),
- 'attendance' => preg_split('//', mb_substr($line, -7), -1, PREG_SPLIT_NO_EMPTY)
- ];
- }
- }
- print_r ($fulldiary->parse($input));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement