. */ declare(strict_types=1); namespace App\Services\CSV\Converter; use Carbon\Carbon; use Carbon\Language; use Exception; use InvalidArgumentException; /** * Class Date */ class Date implements ConverterInterface { private string $dateFormat; private string $dateFormatPattern; private string $dateLocale; /** * Date constructor. */ public function __construct() { $this->dateFormat = 'Y-m-d'; $this->dateLocale = 'en'; $this->dateFormatPattern = '/(?:('.join("|", array_keys(Language::all())).')\:)?(.+)/'; } /** * Convert a value. * * @param $value * * @return string * */ public function convert($value) { $string = app('steam')->cleanStringAndNewlines($value); $carbon = null; if ('!' !== $this->dateFormat[0]) { $this->dateFormat = sprintf('!%s', $this->dateFormat); } if ('' === $string) { app('log')->warning('Empty date string, so date is set to today.'); $carbon = today(); $carbon->startOfDay(); } if ('' !== $string) { app('log')->debug(sprintf('Date converter is going to work on "%s" using format "%s"', $string, $this->dateFormat)); try { $carbon = Carbon::createFromLocaleFormat($this->dateFormat, $this->dateLocale, $string); } catch (InvalidArgumentException|Exception $e) { app('log')->error(sprintf('%s converting the date: %s', get_class($e), $e->getMessage())); return Carbon::today()->startOfDay()->format('Y-m-d H:i:s'); } } return $carbon->format('Y-m-d H:i:s'); } /** * Add extra configuration parameters. * * @param string $configuration */ public function setConfiguration(string $configuration): void { [$this->dateLocale, $this->dateFormat] = $this->splitLocaleFormat($configuration); } /** * @param string $format * * @return array */ public function splitLocaleFormat(string $format): array { $currentDateLocale = 'en'; $currentDateFormat = 'Y-m-d'; $dateFormatConfiguration = []; preg_match($this->dateFormatPattern, $format, $dateFormatConfiguration); if (3 === count($dateFormatConfiguration)) { $currentDateLocale = $dateFormatConfiguration[1] ?: $currentDateLocale; $currentDateFormat = $dateFormatConfiguration[2]; } return [$currentDateLocale, $currentDateFormat]; } }