[ "name" => "date", "regex" => "/^[[:digit:]]{4}(-[[:digit:]]{2}){2} [[:digit:]]{2}(:[[:digit:]]{2}){2}$/", "sqlType" => "datetime", ], "Numer abonenta" => [ "name" => "number", "regex" => "/^[[:digit:]]{11}$/", "sqlType" => "varchar(11)", ], "Koszt netto" => [ "name" => "cost", "regex" => "/^[[:digit:]]+,[[:digit:]]{2}$/", "sqlType" => "decimal(10,2)", "replace" => [ "from" => ",", "to" => ".", ], ], ]; public function handleAuth() { if (!User::logged()) { throw new HttpException('Unauthorized', 401); } } private function parseCsv($file) { if (!file_exists($file)) Throw new Exception("CSV file error #1 - File not found."); $csv = array_map(function ($line) { return str_getcsv(trim($line), ";"); }, file($file)); array_walk($csv, function(&$a) use ($csv) { if (count($csv[0]) != count($a)) throw new Exception("CSV file error #2 - Wrong fields count."); $a = array_combine($csv[0], $a); }); array_shift($csv); $csv = array_filter($csv, function($a) { if (($a['TG wych.'] == '-1') || (!$a['TG wych.'])) return false; if ($a['Koszt netto'] == '0,00') return false; return true; }); array_walk($csv, function(&$a) { $result = []; foreach ($this->fields as $k => $v) { if (!isset($a[$k])) throw new Exception("CSV file error #3 - Field \"{$k}\" not found."); if (!preg_match($v["regex"], $a[$k])) throw new Exception("CSV file error #4 - Bad value of \"{$k}\" ({$a[$k]})."); if (isset($v["replace"])) $result[$v["name"]] = str_replace($v["replace"]["from"], $v["replace"]["to"], $a[$k]); else $result[$v["name"]] = $a[$k]; } $a = $result; }); return array_values($csv); } private function importCsv() { if (!isset($_FILES['csv'])) throw new Exception("Błąd formularza"); if ($_FILES['csv']['type'] != "text/csv") throw new Exception("Błędny plik CSV"); $csv = $this->parseCsv($_FILES['csv']['tmp_name']); $csvPost = base64_encode(gzcompress(json_encode($csv))); $_SESSION['VoIPAmsImportReady'] = true; ?>