<?php
namespace ModulesAbstract\PluginReports\Report\Model\Exporter; abstract class ExporterAutoFileManagement extends ExporterWithStorageAbstract { protected $openFiles= []; public function destroy() { if ($this->openFiles) { foreach ($this->openFiles as $key => $handler) { fclose($handler); unset($this->openFiles[$key]); } $this->openFiles= []; } parent::destroy(); } protected function fileOpen($filename) { if (!isset($this->openFiles[$filename])) { $file = fopen($this->basePath.$filename, "w" ); if ($file===false) { throw new \Exception(sprintf("Cannot open report file. Path: %s", $this->basePath.$filename)); } $this->openFiles[$filename] = $file; } return $this->openFiles[$filename]; } protected function fileAppend($filename, $str) { $file = $this->fileOpen($filename); if (fwrite($file, $str)===false) { throw new \Exception(sprintf("Cannot write to report file. Path: %s", $this->basePath.$filename)); } } protected function getCSVLine($filename, array $fields, string $separator = ",", string $enclosure = "\"", string $escape = "\\", string $eol = "\n") { array_walk($fields, [$this, 'filePutCSV_dataEncoder'], [ 'enclosure' => $enclosure, 'escape' => $escape, ]); $line = implode($separator, $fields) . $eol; return $line; } public function filePutCSV_dataEncoder(&$inputValue, $index, $args) { $useEnclosure = false; $regexp = sprintf("/[\s%s%s]/", preg_quote($args['enclosure']), preg_quote($args['escape'])); if (preg_match($regexp, $inputValue)) { $useEnclosure = true; } $replacements = [ $args['escape'].$args['enclosure'] => $args['escape'].$args['enclosure'], $args['enclosure'] => $args['enclosure'].$args['enclosure'], ]; $inputValue = str_replace(array_keys($replacements), array_values($replacements), $inputValue); if ($useEnclosure) { $inputValue = $args['enclosure'] . $inputValue . $args['enclosure']; } } }