$id], $data ); $data = $this->cleanInputData($data); $this->openFile(); $this->update($id, $data); return $this; } /** * Check if $input keys are constants of Storage * Set input keys as empty value if not exists * @param array $input * @return array */ protected function cleanInputData(array $input) { $columns = $this->getColumns(); foreach ($columns as $column) { if (!isset($input[$column])) { $input[$column] = ''; } } return $input; } /** * Handle csv file, create it if not exists (with column name) * @throws StorageException * @return string */ private function openFile() { $file = $this->getOption('filename'); $fileExists = file_exists($file); if (($this->handle = fopen($file, 'a+')) !== false) { if (!$fileExists) { fputcsv($this->handle, $this->getColumns(),';'); fseek($this->handle, 0); } return; } throw new StorageException('Unable to open csv file'); } /** * Return an array of Storage constant var * @return array * @throws StorageException */ private function getColumns() { $class = new \ReflectionClass(__CLASS__); $constants = $class->getConstants(); $columns = []; foreach ($constants as $constant => $value) { if (strpos($constant, 'DIAGNOSTIC_') === 0) { array_push($columns, $value); } } if (empty($columns)) { throw new StorageException('No column to fill into CSV storage'); } return $columns; } /** * Copy csv data into tmp file with updated line referenced by $id * Copy tmp file to csv && remove tmp file * @param $id * @param $entityData * @return bool|string|void * @throws StorageException */ private function update($id, $entityData = []) { $tmpFile = \tao_helpers_File::createTempDir() . 'store.csv'; $tmpHandle = fopen($tmpFile, 'w'); $line = 1; $index = 0; while (($data = fgetcsv($this->handle, 1000, ";")) !== false) { if ($line === 1) { $keys = $data; if (($index = array_search('id', $keys, true)) === false) { return false; } } if ($data[$index] == $id) { foreach($data as $index => $value){ if (empty($entityData[$keys[$index]])) { $entityData[$keys[$index]] = $value; } } } else { fputcsv($tmpHandle, $data, ';'); } $line++; } $entityData = array_merge(array_flip($keys), $entityData); fputcsv($tmpHandle, $entityData, ';'); fclose($tmpHandle); fclose($this->handle); \tao_helpers_File::copy($tmpFile, $this->getOption('filename')) && unlink($tmpFile); return; } public function flush() { $file = $this->getOption('filename'); if(file_exists($file)){ return unlink($file); } return true; } }