Advertisement
Guest User

success

a guest
Jan 20th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.81 KB | None | 0 0
  1. <?php
  2. $input=file_get_contents ('C:\wamp64\www\naplo.txt','r')  or
  3. exit('Unable to open the file!');
  4.  
  5. $fulldiary=new DiaryParser();
  6.  
  7. class DiaryRecord
  8. {
  9.  
  10.     /**
  11.      * @var \DateTime
  12.      */
  13.     public $date;
  14.  
  15.     /**
  16.      * @var string
  17.      */
  18.     public $name = '';
  19.  
  20.     /**
  21.      * @var string[]
  22.      */
  23.     public $attendance = [];
  24.  
  25. }
  26. class DiaryParser
  27. {
  28.     /**
  29.      * @var int
  30.      */
  31.     protected $year = 2017;
  32.    
  33.     protected $time='12:00';
  34.  
  35.     /**
  36.      * @return \DiaryRecord[]
  37.      */
  38.     public function parse(string $diary): array
  39.     {
  40.         $records = [];
  41.         $days = explode('# ', trim($diary, "# \t\r\n"));
  42.         $days = array_filter($days);
  43.         foreach ($days as $day) {
  44.             $lines = $this->splitLines($day);
  45.             $date = $this->parseDateLine(array_shift($lines));
  46.             foreach ($lines as $absenceLine) {
  47.                 $absenceLine = $this->parseAbsenceLine($absenceLine);
  48.  
  49.                 $record = new DiaryRecord();
  50.                 $record->date = $date;
  51.                 $record->name = $absenceLine['name'];
  52.                 $record->attendance = $absenceLine['attendance'];
  53.  
  54.                 $records[] = $record;
  55.             }
  56.         }
  57.  
  58.         return $records;
  59.     }
  60.     protected function splitLines(string $text): array
  61.     {
  62.         return explode("\n",trim($text,"\n"));
  63.     }
  64.     protected function parseDateLine(string $line): string
  65.     {
  66.         $d=explode(" ",trim($line));
  67.         return strval($this->year).'-'.$d[0].'-'.$d[1].' '.($this->time);
  68.     }
  69.     protected function parseAbsenceLine(string $line): array
  70.     {
  71.     return [
  72.         'name' => mb_substr($line,0,-8),
  73.         'attendance' => preg_split('//', mb_substr($line, -7), -1, PREG_SPLIT_NO_EMPTY)
  74.     ];
  75.     }
  76.    
  77. }
  78. print_r ($fulldiary->parse($input));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement