<?php
namespace ModulesAbstract\PluginReports\Report\Model; class ErrorReport { protected $fileFullPath = null; private $fh = null; protected $fileHeader = ['report', 'field', 'message', 'value', 'identifiers', 'context', ]; public function __construct($path) { $this->fileFullPath = $path; } protected function openFile($fileHeader) { $this->fh = fopen($this->fileFullPath, "w"); if (!$this->fh) { throw new \Exception("Cannot open for writing {$this->fileFullPath}"); } if (fputcsv($this->fh, $fileHeader, ",", "\"", "") === false) { throw new \Exception("Cannot write to {$this->fileFullPath}"); } } protected function closeFile() { if ($this->fh) { if (!fclose($this->fh)) { throw new \Exception("Cannot close file {$this->fileFullPath}"); } if (!\Engine\File::setDefaultPermissions($this->fileFullPath)) { throw new \Exception("Cannot set permissions for {$this->fileFullPath}"); } } } public function destroy() { $this->closeFile(); } public function log($level, $reportName, $field, $message, $value, array $identifiers = [], array $context = []) { if (!in_array($level, ['error', 'info', 'skip'])) { throw new \Exception(sprintf("Invalid error level: %s", $level)); } if (!$this->fh) { $this->openFile($this->fileHeader); } $errMessage = $this->composeErrorMessage($level, $reportName, $field, $message, $value, $identifiers, $context); if (fputcsv($this->fh, array_values($errMessage), ",", "\"", "")===false) { throw new \Exception("Cannot write to {$this->fileFullPath}"); } } public function logRaw($level, $errMessage) { if (!in_array($level, ['error', 'info', 'skip'])) { throw new \Exception(sprintf("Invalid error level: %s", $level)); } if (!$this->fh) { $this->openFile(array_keys($errMessage)); } if (fputcsv($this->fh, array_values($errMessage), ",", "\"", "")===false) { throw new \Exception("Cannot write to {$this->fileFullPath}"); } } protected function composeErrorMessage($level, $reportName, $field, $message, $value, array $identifiers, array $context) { $ret= []; $ret['report'] = $reportName; $ret['field'] = $field; $ret['message'] = $message; $ret['value'] = $value; $ret['identifiers'] = ($identifiers?json_encode($identifiers, true):''); $ret['context'] = ($context?json_encode($context, true): ''); return $ret; } public function getErrorLogs() { } }