<?php

namespace App\Http\Controllers;

use Illuminate\Routing\Controller as BaseController;

abstract class Controller extends BaseController
{
    protected function csvSafeValue(mixed $value): string
    {
        $str = (string) ($value ?? '');
        if ($str === '') {
            return '';
        }

        $trimmedLeft = ltrim($str);
        if ($trimmedLeft !== '' && preg_match('/^[=\\+\\-@]/', $trimmedLeft)) {
            return "'".$str;
        }

        $first = $str[0] ?? '';
        if ($first === "\t" || $first === "\r" || $first === "\n") {
            return "'".$str;
        }

        return $str;
    }

    protected function csvSafeRow(array $row): array
    {
        $out = [];
        foreach ($row as $value) {
            $out[] = $this->csvSafeValue($value);
        }

        return $out;
    }
}
