<?php
namespace App\Utils\CSV\Reader; class RowFormatter { protected $spreadsheet = null; protected $columnFormats = []; public function __construct(\App\Utils\CSV\Reader\AbstractReader $spreadsheet) { $this->spreadsheet = $spreadsheet; } public function __destruct() { $this->spreadsheet = null; } public function setColumnFormats(array $columnFormats) { $this->columnFormats = $columnFormats; return $this; } public function getColumnFormats() { return $this->columnFormats; } public function preFormat(string $value, string $field, \App\Utils\CSV\Reader\Row $row) { $cfg = $this->columnFormats[$field]; switch ($cfg['type']) { case 'callback': if ($cfg['callback:preFormat']) { return $cfg['callback:preFormat']($cfg, $value, $field, $row); } else { return $value; } break; case 'S': return (string)$value; break; case 'N': return $value; break; case 'NI': case 'NI+': case 'NI-': if ($cfg['formats']) { foreach ($cfg['formats'] as $fmt) { if (preg_match("/^human:(?P<thousandDelimiter>.)?(?P<decimalDelimiter>.)(?P<numberOfDecimals>[0-9]+)/", $fmt, $m)) { $replacements = [ $m['thousandDelimiter'] => '', $m['decimalDelimiter'] => '.', ]; $value = str_replace(array_keys($replacements), array_values($replacements), $value); } } } if (is_numeric($value)) { return (int)$value; } else { return null; } break; case 'NF': case 'NF+': case 'NF-': if ($cfg['formats']) { foreach ($cfg['formats'] as $fmt) { if (preg_match("/^human:(?P<thousandDelimiter>.)?(?P<decimalDelimiter>.)(?P<numberOfDecimals>[0-9]+)/", $fmt, $m)) { $replacements = [ $m['thousandDelimiter'] => '', $m['decimalDelimiter'] => '.', ]; $value = str_replace(array_keys($replacements), array_values($replacements), $value); } } } if (is_numeric($value)) { return (float)$value; } else { return null; } break; case 'D': $dt = null; if ($cfg['formats']) { foreach ($cfg['formats'] as $fmt) { $dt = \DateTime::createFromFormat($fmt, $value); if ($dt) { $errors = $dt->getLastErrors(); if (!$errors['warnings'] && !$errors['errors']) { break; } } } if ($dt) { return $dt->format('Y-m-d'); } } return null; break; } return $value; } public function postFormat($value, $field, \App\Utils\CSV\Reader\Row $row) { return $value; } } 